Paint着色器五

Shader默认的绘制是从画布的左上角开始的,在这里也就是View的左上方

如果我们在画布偏中点的位置绘制,那么显示矩形的起点并非图片的起点

public class ShaderView2 extends View{

    private final Paint mPaint;

    public ShaderView2(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.l);
        // 实例化Bitmap着色器
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mPaint.setShader(bitmapShader);

    }

    @Override
    protected void onDraw(Canvas canvas) {

        // 绘制矩形,使其离边缘保持点距离
        canvas.drawRect(80, 80, 280, 480, mPaint);

    }
}

  

  下面通过设置Shader的位置矩阵来控制其实位置

public class ShaderView2 extends View{

    private final Paint mPaint;

    public ShaderView2(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.l);
        // 实例化Bitmap着色器
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        // 设置矩阵
        Matrix matrix = new Matrix();
        // 向右平移80,向下平移80
        matrix.setTranslate(80, 80);
        bitmapShader.setLocalMatrix(matrix);

        mPaint.setShader(bitmapShader);

    }

    @Override
    protected void onDraw(Canvas canvas) {

        // 绘制矩形,使其离边缘保持点距离
        canvas.drawRect(80, 80, 280, 480, mPaint);

    }
}

  

  下面是原图,这里主要是对于着色器的理解,对于矩阵的用法,后面会单独总结。

  

posted @ 2015-09-07 15:05  轻云沉峰  阅读(169)  评论(0)    收藏  举报