简体   繁体   中英

Android rotating bitmap around center point with cropping the corners

Introduction

Hello everyone!

I'm making an app that will rotate a bitmap that contains the map of my university based on compass changes.

I have a squareish pictucre of my university and nearby area, on my phone it's a bit flattened:

在此处输入图片说明

Now i only need to display the campus area, i achieved that by drawing a Rectangle part of that bitmap on my custom View's canvas:

在此处输入图片说明

The Problem

My issue is that i'm unable to achieve rotating the bitmap around the center point.

Right now rotation by 30 degrees looks like this:

在此处输入图片说明

and it doesn't do it's job at all, the campus disappears from the smaller rectangle.

I wan't the image to be rotated around it's center and i want the corners of the image to go off the canvas, so the campus stays in the same place and rotates nicely.

Current approach

To display the map i have custom View with overriden onDraw method.

@Override
protected void onDraw(Canvas canvas) {
    Rect rekt = new Rect();
    Rect tyrRekt = new Rect();

    super.onDraw(canvas);

    tyrRekt.set(0, 0, canvas.getWidth(), canvas.getHeight());
    rekt.set(350, 370, 1520, 900);

    canvas.drawBitmap(bitmap, rekt, tyrRekt, null);
}

and the bitmap is rotated in AsyncTask to save some memory, RotateTaskParams is an object with oryginal bitmap and degrees:

@Override
protected Bitmap doInBackground(RotateTaskParams... params) {
    Matrix matrix = new Matrix();
    matrix.postRotate(params[0].deg);
    rotateBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(params[0].bmp, 0, 0 ,params[0].bmp.getWidth(), params[0].bmp.getHeight(), matrix, true ));
    return rotateBitmap.get();
}

Things I've tried

I was searching for a lot, read tons of simliar questions here, and tried a lot of answers. What didn't work out for me (maybe i did something wrong)

  • postTranslating matrix (center to the 0,0)
  • rotating canvas
  • postRotate around center of the bitmap

    matrix.postTranslate(params[0].deg, params[0].bmp.getWidth()/2 , params[0].bmp.getHeight()/2);

the params[0].bmp is always a oryginal image.

Thanks in advance!

Just try

matrix.postRotate(90);
Bitmap rotated = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(),
                            originalBitmap.getHeight(), matrix, true);

and in your xml, set android:scaleType="centerCrop" to your ImageView tag. Hope it helps.

帮助我以良好的性能实现所需结果的方法是从位图绘制切换到Google Maps,它的API具备了这里所需的一切

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM