android-不仅可以对齐,而且可以使用setPolyToPoly()

时间:2018-11-26 11:12:25

标签: android image matrix

目标是将图像的四边形区域(由4个点设置)转换为矩形图像。使用Matrix.setPolyToPoly()Bitmap.createBitmap(),我可以对齐整个图像,使点形成一个矩形,但是现在我不知道它在左上角在哪里,所以我无法将其剪掉。

例如,假设4个点是标志的角(青色只是ImageView的背景)

example

这是具有硬编码值的代码,可将标志适合72x48位图。

int w = 72;
int h = 48;
float src[] = {108, 201,
               532, 26,
               554, 301,
               55,  372};
float dst[] = {0, 0,
               w, 0,
               w, h,
               0, h};
Matrix m = new Matrix();
m.setPolyToPoly(src, 0, dst, 0, dst.length >> 1);

Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.img);
ImageView iv1 = findViewById(R.id.testImg1);
iv1.setImageBitmap(b1);

Bitmap b2 = Bitmap.createBitmap(b1, 0, 0, b1.getWidth(), b1.getHeight(), m, true);
ImageView iv2 = findViewById(R.id.testImg2);
iv2.setImageBitmap(b2);

//these coordinates are hand-picked
Bitmap b3 = Bitmap.createBitmap(b2, 132, 208, w, h);
ImageView iv3 = findViewById(R.id.testImg3);
iv3.setImageBitmap(b3);

原始图像(请确保将其保存到res / drawable-nodpi):

original image

1 个答案:

答案 0 :(得分:0)

由于@pskink没有发布他的答案,所以我这样做了。

制作新的Bitmap并保存原始的一个-正是我所需要的,因此这是我的解决方案:

int w = 72;
int h = 48;
float srcPoints[] = {108, 201,
                         532, 26,
                         554, 301,
                         55,  372};
float dstPoints[] = {0, 0,
                     w, 0,
                     w, h,
                     0, h};
Matrix m = new Matrix();
m.setPolyToPoly(srcPoints, 0, dstPoints, 0, dstPoints.length >> 1);
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.macedonia);
Bitmap dstBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(dstBitmap);
canvas.clipRect(0, 0, w, h);
canvas.drawBitmap(srcBitmap, m, null);

但是,如果您不想使用额外的内存,请使用其他方法:

class BD extends BitmapDrawable {
    Matrix matrix = new Matrix();
    int w = 72;
    int h = 48;
    RectF clip = new RectF(0, 0, w, h);

    public BD(Resources res, int resId) {
        super(res, BitmapFactory.decodeResource(res, resId));
        float src[] = {108,201,532,26,554,301,55,372};
        float dst[] = {0,0,w,0,w,h,0,h};
        matrix.setPolyToPoly(src, 0, dst, 0, src.length / 2);
    }

    @Override public int getIntrinsicWidth() {return w;}
    @Override public int getIntrinsicHeight() {return h;}

    @Override
    public void draw(Canvas canvas) {
        canvas.clipRect(clip);
        canvas.drawBitmap(getBitmap(), matrix, null);
    }
}