Android高级渲染Shader-BitmapShader

2020-07-03 10:52:17 浏览数 (1)

我们在自定义控件的onDraw()方法中,使用Canvas的drawXX方法画各种形状,而画笔的Shader是用于图形的着色和外观,Shader即着色器
BitmapShader--位图图像渲染,用BitMap对绘制的图形进行渲染着色,简单来说就是用图片对图形进行贴图
代码语言:javascript复制
    /**
     * 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(@NonNull Bitmap bitmap, @NonNull TileMode tileX, @NonNull TileMode tileY) {
        this(bitmap, tileX.nativeInt, tileY.nativeInt);
    }
实例化BitmapShader需要三个参数
  • Bitmap
  • X轴的拉伸模式
  • Y轴的拉伸模式
拉伸模式分为三种
  • CLAMP --是拉伸最后一个像素铺满
  • MIRROR ---是横向纵向不足处不断翻转镜像平铺
  • REPEAT ---类似电脑壁纸,横向纵向不足的重复放置
CLAMP模式
代码语言:javascript复制
    private void drawClampBitmapShader(Canvas canvas){
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
        paint.setShader(bitmapShader);

        RectF rect = new RectF(0,0,800,100);
        canvas.drawRect(rect,paint);
    }

CLAMP效果.jpg

MIRROR模式
代码语言:javascript复制
    private void drawMirrorBitmapShader(Canvas canvas) {
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.MIRROR,Shader.TileMode.MIRROR);
        paint.setShader(bitmapShader);

        RectF rect = new RectF(0,0,1000,1000);
        canvas.drawRect(rect,paint);
    }

MIRROR效果.jpg

REPEAT模式
代码语言:javascript复制
    private void drawRepeatBitmapShader(Canvas canvas) {
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.REPEAT,Shader.TileMode.REPEAT);
        paint.setShader(bitmapShader);

        RectF rect = new RectF(0,0,1000,1000);
        canvas.drawRect(rect,paint);
    }

REPEAT效果.jpg

项目地址:https://gitee.com/aruba/ShaderApplication.git

0 人点赞