Activity
的背景。 我希望背景是全屏图像(无边框)。由于我希望图像填满整个活动背景而不拉伸/压缩(即X和Y的不成比例缩放),并且如果必须裁剪照片,我正在使用
RelativeLayout
与ImageView
(具有android:scaleType ="centerCrop"
)和其余布局包括ScrollView
及其子项。<!-- Tried this with a FrameLayout as well... -->
<RelativeLayout>
<!-- Background -->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<!-- Form -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView>
<LinearLayout>
...
<EditText/>
</LinearLayout>
</ScrollView>
</LinearLayout>
</RelativeLayout>
问题在于布局中还有一些
EditText
视图,当软键盘弹出时,ImageView会被重新调整大小。我希望背景保持不变,无论软键盘是否可见。我在SO上看到很多问题关于ImageView被重新调整大小,但(在我看来)没有令人满意的答案。它们大多数只是设置
android:windowSoftInputMode="adjustPan"
- 这并不总是实用的,特别是如果您希望用户能够在活动中滚动 - 或使用getWindow().setBackgroundDrawable()
,这不会裁剪图像。我已经成功地子类化了ImageView,并重写了它的
onMeasure()
(请参见我的答案:ImageView resizes when keyboard open),以便根据标志强制设定固定的高度和宽度 - 等于设备的屏幕尺寸,但我想知道是否有更好的方法来实现我想要的结果。所以,总的来说,我的问题是:如何将Activity的背景设置为全屏照片
使用scale type = "centerCrop",使得照片等比例缩放(保持其宽高比),因此宽度和高度都将等于或大于视图的相应尺寸;
当软键盘弹出时不会被重新调整大小;
答案:
最终我采用了@pskink的建议,子类化了BitmapDrawable
(请参见他下面的回答)。我必须进行一些调整,以确保BackgroundBitmapDrawable
始终按照填充屏幕的方式进行缩放和裁剪。
这是我的最终类,改编自他的回答:
public class BackgroundBitmapDrawable extends BitmapDrawable {
private Matrix mMatrix = new Matrix();
private int moldHeight;
boolean simpleMapping = false;
public BackgroundBitmapDrawable(Resources res, Bitmap bitmap) {
super(res, bitmap);
}
@Override
protected void onBoundsChange(Rect bounds) {
if (bounds.height() > moldHeight) {
moldHeight = bounds.height();
Bitmap b = getBitmap();
RectF src = new RectF(0, 0, b.getWidth(), b.getHeight());
RectF dst;
if (simpleMapping) {
dst = new RectF(bounds);
mMatrix.setRectToRect(src, dst, ScaleToFit.CENTER);
} else {
// Full Screen Image -> Always scale and center-crop in order to fill the screen
float dwidth = src.width();
float dheight = src.height();
float vwidth = bounds.width();
float vheight = bounds.height();
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * 0.5f;
}
mMatrix.setScale(scale, scale);
mMatrix.postTranslate(dx, dy);
}
}
}
@Override
public void draw(Canvas canvas) {
canvas.drawColor(0xaa00ff00);
canvas.drawBitmap(getBitmap(), mMatrix, null);
}
}
然后,只需创建一个
BackgroundBitmapDrawable
并将其设置为根视图的背景即可。