自定義View繪畫一個圓形
實現步驟:
步驟一:
創建一個類circle繼承View
public class cicle extends View { // 定義畫筆
Paint paint; public cicle(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } // 重寫draw方法
@Override public void draw(Canvas canvas) { super.draw(canvas); // 實例化畫筆對象
paint = new Paint(); // 給畫筆設置顏色
paint.setColor(Color.RED); // 設置畫筆屬性 // paint.setStyle(Paint.Style.FILL);//畫筆屬性是實心圓
paint.setStyle(Paint.Style.STROKE);//畫筆屬性是空心圓
paint.setStrokeWidth(8);//設置畫筆粗細
/*四個參數: 參數一:圓心的x坐標 參數二:圓心的y坐標 參數三:圓的半徑 參數四:定義好的畫筆 */ canvas.drawCircle(getWidth() / 2, getHeight() / 2, 200, paint); } }
步驟二:
將自定義好的類circle在主類的布局文件中引用
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.contentprovide.liuliu.clock.MainActivity">
<com.contentprovide.liuliu.clock.cicle android:layout_width="match_parent" android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
上兩種實現效果: