二十四、图形特效处理—Matrix

Matrix是Android提供的一个矩阵工具类,它本身并不能对图形或组件进行变换,但它可与其他API结合来控制图形、组件的变换。

setTranslate(float dx, float dy)
//平移
setScale(float sx, float sy, float px, float py)
setScale(float sx, float sy)
//放缩
setRotate(float degrees, float px, float py)
setRotate(float degrees)
//旋转
setSkew(float kx, float ky, float px, float py)
setSkew(float kx, float ky)
//倾斜
Matrix不仅可以用于控制图形变形,也可以控制View变形。
    private Bitmap bitmap;

    private Matrix matrix = new Matrix();
    //设置倾斜度
    private float sx = 0.0f;
    //位图的宽和高
    private int width, height;
    //缩放比例
    private float scale = 1.0f;
    //判断缩放还是旋转
    private boolean isScale = false;

    public MatrixView(Context context) {
        super(context);
        init(context);
    }

    public MatrixView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MatrixView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        bitmap = ((BitmapDrawable)context.getResources().getDrawable(R.drawable.switcher3)).getBitmap();
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        this.setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        matrix.reset();
        if(!isScale){
            //旋转
            matrix.setSkew(sx, 0);
        }else{
            //放缩
            matrix.setScale(scale, scale);
        }
        //根据原始位图和Matrix创建新图片
        Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        canvas.drawBitmap(bitmap2, matrix, null);
    }

    public void leftTilt(){
        isScale = false;
        sx += 0.1;
        postInvalidate();
    }

    public void rightTilt(){
        isScale = false;
        sx -= 0.1;
        postInvalidate();
    }

    public void enlarge(){
        isScale = true;
        if(scale < 2.0){
           scale += 0.1;
        }
        postInvalidate();
    }

    public void narrow(){
        isScale = true;
        if(scale > 0.5){
            scale -= 0.1;
        }
        postInvalidate();
    }

效果如图:


你可能感兴趣的:(二十四、图形特效处理—Matrix)