创建一个dorw类继承View,实现构造函数和onDraw方法:
public class dorw extends View {
/**
* @param context
*/
public dorw(Context context) {
super(context);
}
/**
* 在画布上绘制视图
*
* @param canvas
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 在画布上绘制圆形
Paint paint = new Paint();
//设置抗锯齿
paint.setAntiAlias(true);
//设置画笔颜色
paint.setColor(0xffff0000);
//设置画笔模式为填充
paint.setStyle(Paint.Style.STROKE);
//设置画笔宽度
paint.setStrokeWidth(5);
//TODO:绘制圆形
canvas.drawCircle(this.getWidth() >> 1, this.getHeight() >> 1, this.getWidth() >> 1, paint);
//TODO:绘制一个圆点
paint.setAntiAlias(true);
paint.setColor(0xff000000);
paint.setStrokeWidth(10);
canvas.drawPoint(this.getWidth() >> 1, this.getHeight() >> 1, paint);
//TODO:绘制一个十字架
paint.setAntiAlias(true);
paint.setColor(0xff000000);
paint.setStrokeWidth(5);
canvas.drawLine(this.getWidth() >> 1, 0, this.getWidth() >> 1, this.getHeight(), paint);
canvas.drawLine(0, this.getHeight() >> 1, this.getWidth(), this.getHeight() >> 1, paint);
}
}
实例化dorw类,然后查找组件,把dorw类的对象加入到组件里面:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TODO:获取LinearLayout实例
LinearLayout linearLayout = findViewById(R.id.line1);
//TODO:创建一个dorw类的对象
View v = new dorw(this);
//TODO:将dorw类的对象添加到linearLayout中
linearLayout.addView(v);
}
}
xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/line1"
android:layout_width="30dp"
android:layout_height="30dp"
android:orientation="vertical"
android:padding="2dp" />
</LinearLayout>
效果图:
THE END