</pre><p></p><p></p><pre name="code" class="java"> private Bitmap drawSubBitmap(int drawText,Drawable mIcon) { final Bitmap thumb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(); canvas.setBitmap(thumb); Rect r = new Rect(0, 0, width, height); mIcon.setBounds(r); mIcon.draw(canvas); int x = (int) ((width - textWidth) * 0.5); FontMetrics fm = mPaint.getFontMetrics(); int y = (int) ((height - (fm.descent - fm.ascent)) * 0.5 - fm.ascent); canvas.drawText(endstr, x, y - mOffsetY, mPaint); return thumb; }
上面函数的功能是在一个Drawable 的右上角 画上一个数字,然后返回一个bitmap,注意这个Canva是new 出来的。
==============
当我们通过 View.setScale() setAlpha()等方法 或者 调用scrollTo的时候,该方法内部会执行invalidate(),最终会执行View.onDraw()方法。
View.invalidate----->ViewParent:invalidateChild---------->ViewGroup:invalidateChild
------->ViewGroup:dispatchDraw
--->ViewGroup:drawChild(根据View的scale alpha left top等属性操作canvas[平移 缩放 旋转],重新绘制View)
---->View.draw(Canvas canvas)
View.draw(Canvas canvas)代码截取:
if (!verticalEdges && !horizontalEdges) { // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); // we're done... return; }
View绘制的三种方式:
1.设置View属性,执行draw
protected void dispatchDraw(Canvas canvas) { canvas.save() canvas.clipRect(mScrollX, mScrollY, mScrollX + mRight - mLeft, mScrollY + mBottom - mTop); canvas.translate(offset, 0); v.setTranslationX(0); v.setAlpha(1.0f); v.setRotationY(0); drawChild(canvas, getPageAt(childCount - 1), drawingTime); canvas.translate(-offset, 0); canvas.restore(); }
2.直接操作canvas,执行draw
canvas.save() canvas.clipRect(mScrollX, mScrollY, mScrollX + mRight - mLeft, mScrollY + mBottom - mTop); canvas.translate(offset, 0); canvas.rotate(degrees) canvas.scale(sx, sy) drawChild(canvas, getPageAt(childCount - 1), drawingTime); canvas.translate(-offset, 0); canvas.restore();
3.构建Matrix 或者 Transformation(不是setTranslationX ),作用于cavas,执行draw
Matrix matrix = new Matrix(); matrix .setRotate(10); canvas.concat(matrix); drawChild(canvas, getPageAt(childCount - 1), drawingTime);