参考文章链接:
自定义控件其实很简单1/3
Android BitmapShader 实战 实现圆形、圆角图片
这两天在看android中android.graphics.Paint
类的时候关注到一个方法:
/**
* Set or clear the shader object.
* <p />
* Pass null to clear any previous shader.
* As a convenience, the parameter passed is also returned.
*
* @param shader May be null. the new shader to be installed in the paint
* @return shader
*/
public Shader setShader(Shader shader) {
long shaderNative = 0;
if (shader != null)
shaderNative = shader.getNativeInstance();
native_setShader(mNativePaint, shaderNative);
mShader = shader;
return shader;
}
它的作用呢,就是为画笔着色,现在我们先看一个着色器 BitmapShader
,它的构造方法如下:
/**
* Call this to create a new shader that will draw with a bitmap.
*
* @param bitmap The bitmap to use inside the shader
* @param tileX The tiling mode for x to draw the bitmap in.
* @param tileY The tiling mode for y to draw the bitmap in.
*/
public BitmapShader(Bitmap bitmap, TileMode tileX, TileMode tileY) {
mBitmap = bitmap;
mTileX = tileX;
mTileY = tileY;
final long b = bitmap.ni();
init(nativeCreate(b, tileX.nativeInt, tileY.nativeInt));
}
构造方法中的三个参数,第一个是一个Bitmap对象,而另外两个是什么鬼?我翻了源码之后发现它是在BitmapShader类内定义的一个枚举类型,如下:
public enum TileMode {
/**
* 拉伸最后一排或一列像素
* replicate the edge color if the shader draws outside of its
* original bounds
*/
CLAMP (0),
/**
* repeat the shader's image horizontally and vertically
*/
REPEAT (1),
/**
* repeat the shader's image horizontally and vertically, alternating
* mirror images so that adjacent images always seam
*/
MIRROR (2);
TileMode(int nativeInt) {
this.nativeInt = nativeInt;
}
final int nativeInt;
}
代码很简洁,意思也很明了,TileMode的取值有三种:
CLAMP 拉伸 这个和电脑屏保的模式应该有些不同,这个拉伸的是图片边缘的那列或一行像素
REPEAT 重复 就是横向、纵向不断重复这个bitmap
MIRROR 镜像 横向不断翻转重复,纵向不断翻转重复
那我们通过下面这张图片来实际看一下BitmapShader
的使用:
首先,我们先初始化Paint对象:
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mPaintBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cat);
mPaint.setShader(new BitmapShader(mPaintBitmap, TileMode.CLAMP, TileMode.CLAMP));
然后在onDraw方法中,用这个Paint对象画出来:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
}
未完待续