1.自定义view上显示的图像图形都是画在这个view对应的Bitmap实例上的。初始化一个view时,产生了对应的唯一的一个bitmap实例。
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
Paint paint=new Paint();
paint.setColor(Color.RED);
paramCanvas.drawRect(0, 0, 50, 50, paint);
}
这里在view画一个范围为(0,0,50,50)的红色矩形
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
//新建一个bitmap对象
Bitmap bitmap=Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
//将画布的Bitmap改成新建的bitmap
paramCanvas.setBitmap(bitmap);
Paint paint=new Paint();
paint.setColor(Color.RED);
paramCanvas.drawRect(0, 0, 50, 50, paint);
}
然后实例化一个新的Bitmap,将该Bitmap设置为画布的Bitmap,运行效果为全是黑的,因为矩形画在了在内存中新生成的bitmap中了,而不是这个view对象上的bitmap
2.画布canvas的宽高对应它的setBitmap的bitmap的大小,而view对应的bitmap实例的宽高就是view实例化后的大小
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
new AlertDialog.Builder(context)
.setTitle("标题")
.setMessage("画布宽:"+Integer.toString(paramCanvas.getWidth())+" view宽:"+Integer.toString(this.getWidth()))
.setPositiveButton("确定", null)
.show();
}
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
//新建一个bitmap对象
Bitmap bitmap=Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
//将画布的Bitmap改成新建的bitmap
paramCanvas.setBitmap(bitmap);
new AlertDialog.Builder(context)
.setTitle("标题")
.setMessage("画布宽:"+Integer.toString(paramCanvas.getWidth())+" view宽:"+Integer.toString(this.getWidth()))
.setPositiveButton("确定", null)
.show();
}
3.通过画布canvas画图是按先后顺序从下往上叠加的
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
Paint paint=new Paint();
paint.setColor(Color.RED);
paramCanvas.drawRect(0, 0, 50, 50, paint);
paint.setColor(Color.BLUE);
paramCanvas.drawRect(10, 10, 100, 100, paint);
}
红色先画,所以被蓝色覆盖在下面了
4.通过画布画位图Bitmap进行叠加
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
Paint paint=new Paint();
paint.setColor(Color.BLUE);
paramCanvas.drawRect(10, 10, 100, 100, paint);
//新建一个bitmap对象
Bitmap bitmap=Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
Canvas canvas=new Canvas(bitmap);
paint.setColor(Color.RED);
//通过新的画布,将矩形画新的bitmap上去
canvas.drawRect(0, 0, 50, 50, paint);
paramCanvas.drawBitmap(bitmap, 0, 0, paint);
}
先画的蓝色矩形被后画的位图bitmap覆盖了
将位图bitmap的底色改为透明
protected void onDraw(Canvas paramCanvas) {
super.onDraw(paramCanvas);
Paint paint=new Paint();
paint.setColor(Color.BLUE);
paramCanvas.drawRect(10, 10, 100, 100, paint);
//新建一个bitmap对象,设置为Config.ARGB_8888底色为透明
Bitmap bitmap=Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas canvas=new Canvas(bitmap);
paint.setColor(Color.RED);
//通过新的画布,将矩形画新的bitmap上去
canvas.drawRect(0, 0, 50, 50, paint);
paramCanvas.drawBitmap(bitmap, 0, 0, paint);
}
因为位图底色透明了,所以只有有颜色的红色矩形区域遮住了先画的蓝色矩形,其他区域因为透明的底色,所以下面可见