1 @Override
2 protected void onDraw(Canvas canvas) {
3 if (!mIsDrawing) {
4 mIsDrawing = true;
5
6 //组件的宽度和高度,即图片显示区域的大小
7 int width = getWidth();
8 int height = getHeight();
9
10 if (mBitmap == null || width <= 0 || height <= 0) {
11 return;
12 }
13
14 //创建一个和显示区域大小相同的位图
15 Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
16 Canvas bmpCanvas = new Canvas(bmp);
17
18 try {
19 //计算切图的宽度、高度
20 int srcWidth = getRealSrcWidth();
21 int srcHeight = getRealSrcHeight();
22
23 //计算切图的X、Y坐标
24 int srcOffsetX = mOffsetX;
25 int srcOffsetY = mOffsetY;
26 if (srcOffsetY + srcHeight > mBitmap.getHeight()) {
27 srcOffsetY = mBitmap.getHeight() - srcHeight;
28 }
29
30 //计算目标显示区域绘制的宽度、高度
31 int desWidth = getRealDesWidth();
32 int desHeight = getRealDesHeight();
33
34 //计算目标显示区域绘制的X、Y坐标
35 int desOffsetX = Math.max(0, (width - desWidth) / 2);
36 int desOffsetY = 0;
37 if (desHeight < height) {
38 desOffsetY = Math.max(0, (height - desHeight) / 2);
39 }
40
41 //绘制切图图片背景,切图大小小于显示区域时需要
42 if (mDrawScale < 1 || desHeight < height) {
43 Paint fillPaint = new Paint();
44 fillPaint.setColor(Color.BLACK);
45 bmpCanvas.drawRect(0, 0, width, height, fillPaint);
46 }
47
48 //绘制切图图片
49 bmpCanvas.drawBitmap(mBitmap,
50 new Rect(srcOffsetX, srcOffsetY, srcOffsetX + srcWidth, srcOffsetY + srcHeight),
51 new Rect(desOffsetX, desOffsetY, desOffsetX + desWidth, desOffsetY + desHeight),
52 null);
53
54 //将切图图片绘制到画布
55 canvas.drawBitmap(bmp,
56 new Rect(0, 0, bmp.getWidth(), bmp.getHeight()),
57 new Rect(0, 0, width, height),
58 null);
59
60 //销毁切图图片,重要
61 bmp.recycle();
62 }
63 catch (Exception exp) {
64 }
65 finally {
66 mIsDrawing = false;
67 }
68 }
69 }