赞
踩
onDraw方法通过Canvas对象在View上绘制不同的东西(直线,圆形,矩形...)
1.自定义View类
- public class MyViews extends View {
-
- private Paint paint;
-
- public MyViews(Context context) {
- super(context);
- init();
- }
-
- public MyViews(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
-
- private void init(){
- paint = new Paint();
- paint.setAntiAlias(true);//抗锯齿
- paint.setColor(Color.RED);//画笔颜色
- paint.setStyle(Paint.Style.FILL);//画笔风格
- paint.setTextSize(30);//绘制文字大小,单位px
- paint.setStrokeWidth(5);//画笔粗细
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- canvas.drawColor(Color.GREEN);
- canvas.drawCircle(getWidth()/2, getWidth()/2, getWidth()/2, paint);//画实心圆
- }
- }

布局
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <com.wjn.myview.view.MyViews
- android:layout_width="200dp"
- android:layout_height="200dp"
- android:layout_gravity="center"
- android:layout_marginTop="100dp" />
-
-
- </LinearLayout>
效果
即:在onDraw方法中使用画笔和画布先画一个正方形再画一个实心圆。
心得
自定义onDraw方法主要用来绘制View,所以需要配合Canvas(画布)和Paint(画笔)一起结合使用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。