简体   繁体   English

在圆圈内绘制文字

[英]Draw text inside a circle

I'm working on an Android application and I want to draw a circle with text inside. 我正在开发一个Android应用程序,我想绘制一个带有文本的圆圈。 I want the fill to be white with a black boarder and black text. 我希望填充为白色,黑色边框和黑色文字。 Right now I have a ShapeDrawable : 现在我有一个ShapeDrawable

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

This however makes the whole circle white (and with a white background you can't see it) and after a while searching as to how you can add text to the shape I can't seem to find an answer that works. 然而,这会使整个圆圈变白(并且白色背景你看不到它),经过一段时间的搜索,你怎么能在形状上添加文字,我似乎无法找到有效的答案。 I should also note that I will be adding an arbitrary number of circles with different text in each based on user input. 我还要注意,我将根据用户输入添加任意数量的不同文本的圆圈。 Any help would be much appreciated! 任何帮助将非常感激!

You can try this alternative method. 您可以尝试这种替代方法。

Create a drawable file oval.xml 创建一个可绘制的文件oval.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>

Then create a RelativeLayout and set the background with the oval drawable 然后创建一个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>

The result will be something like this: 结果将是这样的:

在此输入图像描述

I am sure late to reply here, but this might be helpful to others. 我很肯定在这里回复,但这可能对其他人有所帮助。

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM