在不使用 canvas 的情况下在 android 中绘制圆圈和填充颜色

draw circle and fill color in android without using canvas

我正在使用 Android Studio 2.1.2 创建 android 应用程序。在我的应用程序中,我需要在 android 视图中创建一个用红色填充的圆圈。我尝试使用 canvas 之类的

protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius = x / 2;
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(2);
            canvas.drawPaint(paint);
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }

并且在 onCreate() 中,我添加了,

setContentView(new SampleView(this));

其中 SampleView 是包含 onDraw() 的 class。有没有其他方法可以在不使用 canvas?

的情况下做同样的事情

您可以创建形状 xml 并将其分配给线性布局

类似这样的事情

   <LinearLayout
            android:background="@drawable/circle_border"
            android:layout_width="100dp"
            android:layout_height="100dp">

   </LinearLayout>



<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="false">
         <shape android:shape="oval">
            <solid android:color="@color/red" />
         </shape>
     </item>
</selector>

这会画一个圆

希望对您有所帮助

首先您需要在 drawable.

中创建 custom_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid android:color="@color/red" />

</shape>

然后就可以在layout中使用了

<LinearLayout
    android:id="@+id/button1"
    android:layout_width="20sp"
    android:layout_height="20sp"
    android:layout_gravity="center"
    android:background="@drawable/custom_circle"
    android:padding="5dp"
    android:visibility="gone" />

像这样从 xml 创建一个可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#FF0000"/>
</shape>

如果需要,您还可以在此绘图中设置大小和描边。然后在布局中添加一个 ImageView (或任何你想要的)并为其设置可绘制对象:

<ImageView
        android:src="@drawable/your_drawable" \>