Android中的偏斜矩阵

时间:2014-08-13 13:15:43

标签: android matrix view android-canvas

我正在开发Android项目。我正在使用View类使用带矩阵的画布绘制位图。

我如何扭曲矩阵?是这样的:

enter image description here

我正在使用此代码,但它无效:

float[] src=new float[]{0,0,0,1,1,1,1,0};
float[] dst=new float[]{0.2f,0,0,1,1,1,0.8f,0};
Paint paint = new Paint();
matrix.reset();     
matrix.postTranslate(-width / 2.0f, -height / 2.0f);        
matrix.postRotate(0/*(float)(angle*180/Math.PI) ,-width / 2.0f + 50, -height / 2.0f +50*/);
matrix.postScale(scale, scale); 
matrix.setPolyToPoly(src, 0, dst, 0, 4);
matrix.postTranslate(position.getX(), position.getY());             
canvas.drawBitmap(bitmap, matrix, paint);
canvas.concat(matrix);

1 个答案:

答案 0 :(得分:1)

使用类似的东西:

class V extends View {

    private Bitmap b;
    private Matrix m;

    public V(Context context) {
        super(context);
        b = BitmapFactory.decodeResource(getResources(), R.drawable.layer0);
        m = new Matrix();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        int bw = b.getWidth();
        int bh = b.getHeight();
        float[] src = {0, 0, 0, bh, bw, bh, bw, 0};
        int DX = 100;
        float[] dst = {0 + DX, 0, 0, h, w, h, w - DX, 0};
        m.setPolyToPoly(src, 0, dst, 0, 4);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(b, m, null);
    }
}

更新以保持图像宽高比:

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        int bw = b.getWidth();
        int bh = b.getHeight();
        RectF src = new RectF(0, 0, bw, bh);
        RectF dst = new RectF(0, 0, w, h);
        m.setRectToRect(src, dst, ScaleToFit.CENTER);

        float[] pts = {0, 0, 0, bh, bw, bh, bw, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        m.mapPoints(pts, 8, pts, 0, 4);
        int DX = 40;
        pts[8] += DX;
        pts[14] -= DX;
        m.setPolyToPoly(pts, 0, pts, 8, 4);
    }