Search code examples
androidimageimageviewscaleandroid-screen

How to scale the height but cut off the end of an image in Android ImageView?


This more of a conceptual Android question

Say I have this static image that I want to load into an ImageView -enter image description here

Say the image is 600px by 200px.(width by height)

Say my image view I try fitting it into is 300 px by 200px(width by height)

I just want to scale by height and cut off the left end of the image so that the image can fit into the imageview. Also if no cuts need to take place(fits already), I don't want to cut any of it off.

So in the end the ImageView(if it was 300 px by 200px) would hold this image

enter image description here (basically so the F doesn't get distorted)

I've looked Scale To Fit but none of the scale types seems to achieve this custom effect. Does anyone know of how I would go about this? In my case, I wouldn't want to maintain the original aspect ratio.


Solution

  • You should crop the Bitmap so that it always fits into your ImageView. If you want the bottom-right corner cropped, you could do something similar to this:

    if (needsCropping()) {
        int startWidth = originalImage.getWidth() - 300;
        int startHeight = originalImage.getHeight() - 200;
    
    
        Bitmap croppedBitmap = Bitmap.createBitmap(originalImage, startWidth, startHeight, width, height);
    
        // TODO set imageview
    }