【问题标题】:Draw text inside a circle在圆圈内绘制文本
【发布时间】:2013-11-23 21:21:33
【问题描述】:

我正在开发一个 Android 应用程序,我想在里面画一个带有文本的圆圈。我希望填充为白色,带有黑色边框和黑色文本。现在我有一个ShapeDrawable

mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xFFFFFF);

但是,这会使整个圆圈变白(并且在白色背景下您看不到它),并且在搜索了如何将文本添加到形状之后,我似乎找不到有效的答案。我还应该注意,我将根据用户输入添加任意数量的带有不同文本的圆圈。任何帮助将非常感激!

【问题讨论】:

  • Drawable 不是用来画文字的,你应该试试位图,就像 Geralt 图解的那样
  • 什么??? Drawable 用于绘制可以使用 Canvas 绘制的所有内容

标签: android drawable


【解决方案1】:

你可以试试这个替代方法。

创建一个可绘制的文件椭圆形.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
   <solid android:color="#fff"/>
   <stroke android:width="2px" android:color="#000"/>
</shape>

然后创建一个RelativeLayout并用椭圆形drawable设置背景

<RelativeLayout
    android:id="@+id/circle"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_gravity="center"
    android:background="@drawable/oval" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />
</RelativeLayout>

结果会是这样的:

【讨论】:

  • 我编辑了我的问题以添加一条关键信息,因为我需要多个圆圈,每个圆圈中都有不同的文本。这必须以可编程方式完成,所以我不能简单地将它们硬编码到 xml 文件中
  • 这个答案很棒,因为在stackoverflow.com/questions/10060470/… 中,您被告知将椭圆形可绘制对象设置为 TextView 的背景。但如果你不画一个实心圆,那么 TextView 会触及圆的边缘。所以TextView周围有RelativeLayout的方法要好得多!
  • 如果您不需要在背景周围使用轮廓,请不要使用 RelativeLayout 作为 TextView 的容器。在大多数情况下,这不是必需的。
【解决方案2】:

我肯定会迟到在这里回复,但这可能对其他人有帮助。

    ShapeDrawable colorCode = new ShapeDrawable(new OvalShape());
    colorCode.getPaint().setStyle(Paint.Style.FILL); //See more paint style for border circle etc. like STROKE
    colorCode.getPaint().setAntiAlias(true);
    colorCode.getPaint().setColor(getResources().getColor(YOUR_COLOUR_HERE_FROM_XML));
    colorCode.setIntrinsicHeight(Globals.dp2px(5, getActivity())); //converting dp to px, you can just put any integer instead of dp2px method
    colorCode.setIntrinsicWidth(Globals.dp2px(5, getActivity()));
    greenText.setBackgroundDrawable(colorCode);

【讨论】:

  • setBackgroundDrawable 现已弃用,但只需替换为 setBackground
猜你喜欢
  • 2015-01-31
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2015-07-04
  • 2021-10-15
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多