这不是最高效的解决方案,但正如有人建议的那样,您可以创建 FrameLayout 或 RelativeLayout 并将 ImageView 用作伪背景 - 其他元素将位于其上方:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ImageView
android:id="@+id/ivBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitStart"
android:src="@drawable/menu_icon_exit" />
<Button
android:id="@+id/bSomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="61dp"
android:layout_marginTop="122dp"
android:text="Button" />
</RelativeLayout>
ImageView 的问题是只有 scaleTypes 可用:
CENTER, CENTER_CROP, CENTER_INSIDE, FIT_CENTER,FIT_END, FIT_START, FIT_XY, MATRIX
(http://etcodehome.blogspot.de/2011/05/android-imageview-scaletype-samples.html)
并在某些情况下“缩放背景图像(保持其纵横比)”,当您希望图像填满整个屏幕(例如背景图像)并且屏幕的纵横比与图像不同时,必要scaleType 是一种 TOP_CROP,因为:
CENTER_CROP 将缩放的图像居中,而不是将顶部边缘与图像视图的顶部边缘对齐,并且 FIT_START 适合屏幕高度而不是填充宽度。正如用户 Anke 注意到的那样,FIT_XY 没有保持纵横比。
很高兴有人扩展了 ImageView 以支持 TOP_CROP
public class ImageViewScaleTypeTopCrop extends ImageView {
public ImageViewScaleTypeTopCrop(Context context) {
super(context);
setup();
}
public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
@Override
protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
if (getDrawable() != null) {
Matrix matrix = getImageMatrix();
float scaleFactor, scaleFactorWidth, scaleFactorHeight;
scaleFactorWidth = (float) frameWidth / (float) getDrawable().getIntrinsicWidth();
scaleFactorHeight = (float) frameHeight / (float) getDrawable().getIntrinsicHeight();
if (scaleFactorHeight > scaleFactorWidth) {
scaleFactor = scaleFactorHeight;
} else {
scaleFactor = scaleFactorWidth;
}
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
}
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
https://stackoverflow.com/a/14815588/2075875
现在恕我直言,如果有人编写自定义 Drawable 来像这样缩放图像,那将是完美的。然后它可以用作背景参数。
Reflog 建议在使用前对 drawable 进行预缩放。以下是如何执行此操作的说明:
Java (Android): How to scale a drawable without Bitmap?
虽然它有缺点,但升级后的可绘制/位图将使用更多 RAM,而 ImageView 使用的动态缩放不需要更多内存。优势可能是处理器负载更少。