代码之家  ›  专栏  ›  技术社区  ›  Powercoder

android-使用setPolytoply()不仅可以对齐,还可以切断图像

  •  0
  • Powercoder  · 技术社区  · 6 年前

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

    (青色只是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 回复  |  直到 6 年前
        1
  •  0
  •   Powercoder    6 年前

    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);
        }
    }