paxx
paxx

Reputation: 1079

Scale and crop image in XML

I'm trying to scale and crop image at the same time and show it from left to right screen edge. I receive image that is just little bit wider than users screen and I'm able to scale it like this (XML):

<ImageView
        android:id="@+id/category_image_top"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:maxHeight="170dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true" 
        android:focusable="false"
        />

But this is what I get: What I get

I would like to align image to top right like so: What I want

Is this possible? I've tried all scaleTypes but noting works, image is either scaled to fit by X and Y (fitXY, fitStart) or image cropped but centered (centerCrop). I need something like android:scaleType="cropStart"

Upvotes: 5

Views: 14780

Answers (3)

FiqSky
FiqSky

Reputation: 2298

add

android:layout_gravity="center"

Upvotes: 0

tharinduPro
tharinduPro

Reputation: 109

<ImageView
        android:id="@+id/category_image_top"
        android:layout_width="match_parent"
        android:layout_height="170dp"
        android:maxHeight="170dp"
        android:scaleType="centerCrop"
        android:paddingLeft="half of your screen width"
        android:paddingBottom="half of your screen height"
        android:adjustViewBounds="true" 
        android:focusable="false"
/>

You can set padding to move image left or right and also top and bottom padding to move up and down

Upvotes: 5

paxx
paxx

Reputation: 1079

As I didn't find a way to deal with this situation through xml (views) I turned (as @serenskye suggested) to code. Here's my code, I hope it helps (ps: I've changed my logic a little bit, I wanted to fit image by width so I've scaled it to predefined imageWidght and then cropped it to imageHeight)

//bm is received image (type = Bitmap)
Bitmap scaledImage = null;
float scaleFactor = (float) bm.getWidth() / (float) imageWidth;

//if scale factor is 1 then there is no need to scale (it will stay the same)
if (scaleFactor != 1) {
    //calculate new height (with ration preserved) and scale image
    int scaleHeight = (int) (bm.getHeight() / scaleFactor);                     
    scaledImage = Bitmap.createScaledBitmap(bm, imageWidth, scaleHeight, false);
}
else {
    scaledImage = bm;
}

Bitmap cropedImage = null;
//if cropped height is bigger then image height then there is no need to crop
if (scaledImage.getHeight() > imageHeight)
    cropedImage = Bitmap.createBitmap(scaledImage, 0, 0, imageWidth, imageHeight);
else
    cropedImage = scaledImage;

iv.setImageBitmap(cropedImage);

Upvotes: 1

Related Questions