自定義View畫圓,畫扇形
阿新 • • 發佈:2020-12-31
自定義View畫圓,畫扇形
建立一個類繼承自View
public class lhjclass extends View {
public lhjclass(Context context) {
super(context);
}
public lhjclass(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public lhjclass(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//建立畫筆
Paint paint = new Paint();
//設定畫筆顏色
paint.setColor(Color.WHITE);
//設定畫筆線條
paint.setStrokeWidth(20);
//設定樣式STROKE(空心),FILL(實心)
paint.setStyle(Paint.Style.STROKE);
//畫扇形(true,false表示扇形兩邊的線是否顯示)
canvas.drawArc(320,180,570,430,90,270,false,paint);
//同心圓
/* paint.setColor(Color.WHITE);
canvas.drawCircle(450,300,180,paint);//畫圓
paint.setColor(Color.GREEN);
canvas.drawCircle(450,300,150,paint);*/
}
}
佈局直接使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.a1225.lhjclass
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#1AFF00"
></com.example.a1225.lhjclass>
</LinearLayout>
效果圖