解析画布的clipRect方法

画布的clipRect方法,boolean android.graphics.Canvas.clipRect(int left, int top, int right, int bottom)

在看clipRect方法之前先看看如果将res目录下的图片文件转换为bitmap对象,这里总结了两种方法,大家可以参考使用,

第一种方法,采用BitmapDrawable,

//得到Resources对象 Resources r = this.getContext().getResources(); //以数据流的方式读取资源 InputStream is = r.openRawResource(R.drawable.clock); BitmapDrawable bmpDraw = new BitmapDrawable(is); mBmp = bmpDraw.getBitmap();

第二种方法,采用BitmapFactory,

InputStream is = getResources().openRawResource(R.drawable.icon); Bitmap mBitmap = BitmapFactory.decodeStream(is);

接下来进入主题,看看clipRect方法,

先看段代码:

1 @Override 2 protected void onDraw(Canvas canvas) { 3 super.onDraw(canvas); 4 5 int width = mBmp.getWidth(); 6 int height = mBmp.getHeight(); 7 8 canvas.save(); 9 mPaint.setColor(Color.CYAN); 10 canvas.drawRect(0, 0, width, height, mPaint); 11 canvas.restore(); 12 13 canvas.save(); 14 canvas.clipRect(0, 0, width*2, height*2); 15 canvas.drawBitmap(mBmp, width, height, mPaint); 16 canvas.restore(); 17 }

第14行用到clipRect方法,在这个方法中截取画布的某一个矩形空间,宽和高分别为图片的宽和高的两倍,

image

将第14行的宽度保持不变,高度改成图片高度的1.5倍,

canvas.clipRect(0, 0, width*2, height*3/2);

image

再将闹钟图片画上去,只能画出闹钟的上半部分,下半部分就画不出来了。

posted on 2013-05-20 15:17  勤修  阅读(9646)  评论(0编辑  收藏  举报

导航