0

I'm setting the background of a layout programmatically. How do I center-crop the background?

Bitmap bm = BitmapFactory.decodeFile(myUri);
BitmapDrawable dw = new BitmapDrawable(bm);
layout.setBackgroundDrawable(dw); 

edit

I am looking for the Java equivalent of android:scaleType="centerCrop"

the_prole
  • 8,275
  • 16
  • 78
  • 163

2 Answers2

1

Found an answer here

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger 
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

    return dest;
}
Community
  • 1
  • 1
the_prole
  • 8,275
  • 16
  • 78
  • 163
-1

This is not directly achievable with View backgrounds.

But you have the option to use an ImageView instead and place it behind your actual View using a FrameLayout to 'simulate' a backround. Then you can use centerCrop option:

<FrameLayout  
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <!-- your actual View here -->

</FrameLayout>
Floern
  • 33,559
  • 24
  • 104
  • 119
  • Really? I can't use `android:scaleType="centerCrop"` for a layout? – the_prole Jan 06 '16 at 21:50
  • @the_prole `scaleType` is only available for ImageViews. – Floern Jan 06 '16 at 21:52
  • I tried adding a background to an image view in Java with XML attirbute `android:scaleType="centerCrop"` but I don't see the cropping effect. I don't think I can combine Java and XML in this way. – the_prole Jan 06 '16 at 22:05