age cgg.com.simplecustomview.views; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import cgg.com.simplecustomview.R; /** * author: Wanderer * date: 2018/1/7 20:43 * email: none * <p> * 一般情况下写三个构造方法 让其最终调用有三个参数的构造 * 自定义控件重写的方法: * 1, */ public class MyCustomView extends View { private Paint paint; private Bitmap bitmap; // 供代码创建实例 public MyCustomView(Context context) { this(context, null); } // 供XML布局文件是创建view 有属性参数 public MyCustomView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } // 加了个样式 public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 实例化画笔 paint = new Paint(); // 设置画笔样式 paint.setStyle(Paint.Style.STROKE); // 设置画笔的颜色 paint.setColor(Color.RED); // 解码图片 bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cosplay02); // 修改图pain大小 /**createScaledBitmap: * src 图片 * dstWidth 宽 * dstHeight 高 * filte 是否过滤 */ bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true); } /** * canvas:画布 * drawCircle:参数注释 * float cx, -->圆心的左边距 * float cy, -->圆心的上边距 * float radius, ---> 圈圈的半径 * Paint paint ---> 画笔对象 * <p> * drawRect:绘制矩形 * left和right:矩形左边和右边距离父控件的左边边距 * top和bottom:矩形上边和下边距离父控件的上边边距 * Paint paint */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 画个圈圈 canvas.drawCircle(60, 50, 50, paint); // 画个矩形 canvas.drawRect(10, 110, 100, 160, paint); // 画个图像 canvas.drawBitmap(bitmap,10,180,null); } }
效果图
