我有一个图像,我想把它按宽度填充到整个屏幕,但裁剪图像的顶部,如下所示:
红色区域是图像,红色区域是手机屏幕/父布局。当然,保留纵横比。是否可以在 XML 中而不是以编程方式?
好的,您应该执行以下步骤:-
1). Make Linear Layout
2). apply the image as background
3). set the view at top to crop the background of layout.
我想你明白我在说什么。
例如这是 xml:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white">//background color of your screen
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="put the resource id of the image you want to crop"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@android:color/white" // background color of your screen
/>
</LinearLayout>
</LinearLayout>
请告诉我执行它是否有任何问题..
谢谢欣赏,...
最后我使用自定义视图解决了我的问题:
public class ResizableImageView extends ImageView {
public ResizableImageView(Context context) {
super(context);
}
public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ResizableImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int diw = drawable.getIntrinsicWidth();
if (diw > 0) {
int height = width * drawable.getIntrinsicHeight() / diw;
setMeasuredDimension(width, height);
return;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
并且,XML 文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_margin="0dp"
android:padding="0dp"
tools:context=".SplashActivity" >
<com.xxx.widgets.ResizableImageView
android:id="@+id/imageSplash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="0dp"
android:padding="0dp"
android:src="@drawable/img_splash"
tools:ignore="ContentDescription" />
</RelativeLayout>