畫布的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方法,在這個方法中截取畫布的某一個矩形空間,寬和高分別為圖片的寬和高的兩倍,
將第14行的寬度保持不變,高度改成圖片高度的1.5倍,
canvas.clipRect(0, 0, width*2, height*3/2);
再將鬧鍾圖片畫上去,只能畫出鬧鍾的上半部分,下半部分就畫不出來了。


