BitmapShader用于绘制位图作为纹理的着色器。通过设置平铺模式可以重复或镜像位图。我们会经常用它来实现圆形图片或圆角图片.今天研究一下BitmapShader的用法
BitmapShader的构造方法有三个参数:
1,Bitmap bitmap:位图
2, Shader.TileMode tileX: The tiling mode for x to draw the bitmap in. 在位图x轴显示的方式
3,Shader.TileMode tileY: The tiling mode for y to draw the bitmap in. 在位图y轴显示的方式
Shader.TileMode是一个枚举,有三种方式:
1,Shader.TileMode CLAMP replicate the edge color if the shader draws outside of its original bounds 如果着色器绘制出其原来的边界,复制边缘颜色 其实就是拉伸 但这个拉伸和屏保拉伸不一样,
这个不拉伸图片而是拉伸图片最后的那一个像素;横向的最后一个横行像素,不断的重复,纵项的那一列像素,不断的重复;
2,Shader.TileMode MIRROR repeat the shader’s image horizontally and vertically, alternating mirror images so that adjacent images always seam 重复着色器的图像水平和垂直,交替镜像图像,使相邻的图像总是接缝 实现的镜像效果;
3,Shader.TileMode REPEAT repeat the shader’s image horizontally and vertically 水平和垂直重复着色器的图像 重复效果;
1,CLAMP效果:
大图片:
小图片:
2,MIRROR效果:
3,REPEAT效果:
具体实现代码:
public class BitmapShaderView extends View {
private Paint mPaint;
public BitmapShaderView(Context context) {
this(context,null);
}
public BitmapShaderView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public BitmapShaderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();
}
private void initPaint(){
mPaint = new Paint();
/**
* bitmapshader
*/
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.childinfo_good_state);
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
mPaint.setShader(bitmapShader);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* bitmapshader
*/
canvas.translate(getWidth()/2,getHeight()/2);
canvas.drawCircle(0,0,500,mPaint);
}
}