如何以编程方式中心裁剪布局背景

时间:2016-01-06 21:15:44

标签: android

我以编程方式设置布局的背景。如何对背景进行中心裁剪?

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

修改

我正在寻找与android:scaleType="centerCrop"

等效的Java

2 个答案:

答案 0 :(得分:0)

找到答案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;
}

答案 1 :(得分:-1)

使用View背景无法直接实现。

但您可以选择使用ImageView,并使用FrameLayout将其放置在实际视图后面以“模拟”背景。然后,您可以使用centerCrop选项:

<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>