Android: bitmap rotation leads to black background

前端 未结 1 432
感情败类
感情败类 2021-01-20 14:05

I\'m facing an issue related to Bitmap rotation, issue is follow code rotates the bitmap fine but with a back background when draw rotated bitmap on canvas, I see this only

相关标签:
1条回答
  • 2021-01-20 14:28

    I also get this issue. After Goolge, I find that if you use BitmapFactory.decodeResource,this issue can't be fixed at some devices. So I use these code instead of BitmapFactory.decodeResource:

    Bitmap bitmap = yourBitmap;
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    
    Rect srcR = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    RectF dstR = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
    RectF deviceR = new RectF();
    matrix.mapRect(deviceR, dstR);
    
    int neww = Math.round(deviceR.width());
    int newh = Math.round(deviceR.height());
    
    Bitmap result = Bitmap.createBitmap(neww, newh, Bitmap.Config.ARGB_8888);
    result.eraseColor(Color.TRANSPARENT);
    Canvas canvas = new Canvas();
    canvas.translate(-deviceR.left, -deviceR.top);
    canvas.concat(matrix);
    
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    canvas.setBitmap(result);
    canvas.drawBitmap(bitmap, srcR, dstR, paint);
    canvas.setBitmap(null);
    

    the 'result' Bitmap is your rotated bitmap with transparent BG.

    0 讨论(0)
提交回复
热议问题