##BitmapShader 的作用
官方定义:Shader used to draw a bitmap as a texture
BitmapShader的作用是使用特定的图片来作为纹理来使用。
##简单使用
BitmapShader是Shader的子类,可以通过Paint.setShader(Shader shader)进行设置。
BitmapShader 的构造函数
public BitmapShader(@NonNull Bitmap bitmap, TileMode tileX, TileMode tileY)
三个参数:bitmap 指的是要作为纹理的图片,tileX 指的是在x方向纹理的绘制模式,tileY 指的是Y方向上的绘制模式。
TileMode 源码:
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;
}
CLAMP 拉伸:横向的最后一个横行像素,不断的重复,纵项的那一列像素,不断的重复;
REPEAT 重复:就是横向、纵向不断重复这个bitmap
MIRROR 镜像:横向不断翻转重复,纵向不断翻转重复;
使用:
//创建
BitmapShader shader=new BitmapShader(bitmap,TileMode.CLAMP,TileMode.CLAMP);
Paint paint=new Paint();
//为paint 设置 Shader
paint.setShader(shader);
//这样就可以使用shader的纹理去覆盖绘制的图形的表面了,其中根据:CLAMP,REPEAT,MIRROR,
//来确定纹理的绘制模式
canvas.draw**(***,paint);
##案例
以下demo都用这张图片:
###基本使用
public class ShaderView extends View {
private int mWidth;
private int mHeight;
private BitmapShader bmpShader;
private Paint mPaint;
private RectF bmpRect;
public ShaderView(Context context) {
this(context, null);
}
public ShaderView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ShaderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w; //屏幕宽
mHeight = h; //屏幕高
//Logger.e("w: " + w + " h:" + h + " oldw: " + oldw + " oldh : " + oldh);
bmpRect = new RectF(0, 0, mWidth, mHeight);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dlw);
//Shader.TileMode里有三种模式:CLAMP(拉伸)、MIRROR(镜像)、REPETA(重复)
bmpShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.REPEAT);
mPaint = new Paint((Paint.ANTI_ALIAS_FLAG));
mPaint.setShader(bmpShader); //设置BitmapShader之后相当于绘制了底层的图片背景
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//矩形
canvas.drawRect(bmpRect, mPaint);
}
}
###不同TileMode的展示效果
bmpShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.REPEAT);
bmpShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
bmpShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
</