Crop-to-fit image in Android

前端 未结 3 1832
深忆病人
深忆病人 2020-12-29 00:03

I\'ve been trying this for some time, I would like to create a wallpaper from a Bitmap. Let\'s say the desired wallpaper size is 320x480, and the source image s

相关标签:
3条回答
  • 2020-12-29 00:36

    I know this is an incredibly late reply, but something like this maybe:

    public static Bitmap scaleCropToFit(Bitmap original, int targetWidth, int targetHeight){
        //Need to scale the image, keeping the aspect ration first
        int width = original.getWidth();
        int height = original.getHeight();
    
        float widthScale = (float) targetWidth / (float) width;
        float heightScale = (float) targetHeight / (float) height;
        float scaledWidth;
        float scaledHeight;
    
        int startY = 0;
        int startX = 0;
    
        if (widthScale > heightScale) {
            scaledWidth = targetWidth;
            scaledHeight = height * widthScale;
            //crop height by...
            startY = (int) ((scaledHeight - targetHeight) / 2);
        } else {
            scaledHeight = targetHeight;
            scaledWidth = width * heightScale;
            //crop width by..
            startX = (int) ((scaledWidth - targetWidth) / 2);
        }
    
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, (int) scaledWidth, (int) scaledHeight, true);
    
        Bitmap resizedBitmap = Bitmap.createBitmap(scaledBitmap, startX, startY, targetWidth, targetHeight);
        return resizedBitmap;
    }
    
    0 讨论(0)
  • 2020-12-29 00:55

    here is an answer that gets you most of the way there: How to crop an image in android?

    0 讨论(0)
  • 2020-12-29 00:59

    Thanks to open source, I found the answer from Android Gallery source code here at line 230 :-D

    croppedImage = Bitmap.createBitmap(mOutputX, mOutputY, Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(croppedImage);
    
    Rect srcRect = mCrop.getCropRect();
    Rect dstRect = new Rect(0, 0, mOutputX, mOutputY);
    
    int dx = (srcRect.width() - dstRect.width()) / 2;
    int dy = (srcRect.height() - dstRect.height()) / 2;
    
    // If the srcRect is too big, use the center part of it.
    srcRect.inset(Math.max(0, dx), Math.max(0, dy));
    
    // If the dstRect is too big, use the center part of it.
    dstRect.inset(Math.max(0, -dx), Math.max(0, -dy));
    
    // Draw the cropped bitmap in the center
    canvas.drawBitmap(mBitmap, srcRect, dstRect, null);
    
    0 讨论(0)
提交回复
热议问题