【问题标题】:How to draw polygon in android with text inside如何在带有文本的android中绘制多边形
【发布时间】:2016-12-19 09:52:03
【问题描述】:

我需要用里面的文字来绘制这样的视图。 图形的文字和颜色必须是可变的。 最好的方法是什么?

【问题讨论】:

标签: java android xml android-drawable


【解决方案1】:

一旦你想绘制动态图形,你就进入了手绘领域,或者使用一些 3rd 方库来为你做这件事。

幸运的是,自己动手做起来相当简单。您可以使用Canvas 对象绘制多边形,如this SO post 中的此示例:

Paint wallpaint = new Paint();
wallpaint.setColor(Color.GRAY);
wallpaint.setStyle(Style.FILL);

Path wallpath = new Path();
wallpath.reset(); // only needed when reusing this path for a new build
wallpath.moveTo(x[0], y[0]); // used for first point
wallpath.lineTo(x[1], y[1]);
wallpath.lineTo(x[2], y[2]);
wallpath.lineTo(x[3], y[3]);
wallpath.lineTo(x[0], y[0]); // there is a setLastPoint action but i found it not to work as expected

canvas.drawPath(wallpath, wallpaint);

有几种方法可以将您的 Canvas 附加到将显示在屏幕上的某个 UI 对象,主要在文档Canvas and Drawables 页面中进行了描述,例如

  1. 渲染到Bitmap,然后添加到例如ImageView
  2. 扩展 UI 小部件,例如 View,并在 onDraw 方法中更新它

要更改多边形,只需更改上述lineTo 方法中的x 和y 点以及Paint 中的颜色即可。如果需要,请确保更新,如果您选择方法 1,这可能需要您手动重新渲染到 Bitmap,或者如果您选择方法 2,则在 View 上调用 invalidate

要使文本出现在多边形内,您可以使用 drawText 方法在 Canvas 上绘制,或者在布局 XML 中将 TextView 放在 View 的顶部 / 上。如果您希望文本严格位于多边形内,您显然必须对位置以及可能的换行和截断进行一些计算。

另请参阅 Custom Drawing 手册页。

【讨论】:

    【解决方案2】:

    您可以使用这样的三角形图像来实现它:

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FF2323"
        android:drawableLeft="@drawable/triangle"
        android:gravity="center"
        android:paddingRight="10dp"
        android:text="In Process"
        android:textColor="@android:color/white" />
    

    [] 这是图像。在方括号之间单击以保存它。您将无法在白色背景上看到它,因为它本身就是白色的。

    如果你想调整这个图像的大小,你可以像这样从活动中设置图像:

    textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(getResources(), getResizedBitmap(this, R.drawable.triangle, 64, 64)), null, null, null);
    

    将 64 更改为最适合您的。

    这里是调整大小的方法:

    public static Bitmap getResizedBitmap(Context activity,int imgid,int width,int height) {
        Bitmap bMap = BitmapFactory.decodeResource(activity.getResources(),imgid);
        Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, width,height, true);
        return bMapScaled;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-10
      • 2021-06-30
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多