Patterns指可以使用位图(材质)来填充某个图形。本例使用两个位图来填充屏幕:
一是外蓝里红的矩形
private static Bitmap makeBitmap1() { Bitmap bm = Bitmap.createBitmap(40, 40, Bitmap.Config.RGB_565); Canvas c = new Canvas(bm); c.drawColor(Color.RED); Paint p = new Paint(); p.setColor(Color.BLUE); c.drawRect(5, 5, 35, 35, p); return bm; }
另外一个为绿圆:
private static Bitmap makeBitmap2() { Bitmap bm = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bm); Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); p.setColor(Color.GREEN); p.setAlpha(0xCC); c.drawCircle(32, 32, 27, p); return bm; }
然后创建Shader(类似于GDI中的TextureBrush)
mShader1 = new BitmapShader(makeBitmap1(), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); mShader2 = new BitmapShader(makeBitmap2(), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
public BitmapShader(Bitmap bitmap,Shader.TileMode tileX,Shader.TileMode tileY)
本例创建的两个Shader都是选用的重复平铺模式。当Shader2旋转了30度,所有圆的序列看起来用个角度
Matrix m = new Matrix(); m.setRotate(30); mShader2.setLocalMatrix(m);
此外,为了达到加速绘图,使用PaintFlagsDrawFilter关闭了DITHER_FLAG和FILTER_BITMAP_FLAG
mFastDF = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG, 0);
最后看看onDraw
canvas.setDrawFilter(mDF); mPaint.setShader(mShader1); canvas.drawPaint(mPaint); canvas.translate(mTouchCurrX - mTouchStartX, mTouchCurrY - mTouchStartY); mPaint.setShader(mShader2); canvas.drawPaint(mPaint);
使用Patterns填充是设置Paint的shader属性,
canvas.translate(mTouchCurrX – mTouchStartX,mTouchCurrY – mTouchStartY); 在绘制Shader2( 绿圆)时平移触摸屏移动的距离,效果就是绿圆跟着手指动。