ImageView缩放类型在Android中裁剪图像

时间:2013-11-08 21:47:01

标签: android xml

我有一张图片,我希望按照宽度调整整个屏幕,然后裁剪图像的顶部,如下所示:

enter image description here

红色区域是图像,红色区域是手机屏幕/父级布局。当然,保留纵横比。是否可以用XML而不是编程?

3 个答案:

答案 0 :(得分:1)

好的,你应该这样做: -

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>

如果有任何问题,请告诉我..

谢谢你,...

答案 1 :(得分:1)

使用

android:src="@drawable/img"
android:scaleType="fitEnd"  

而不是

android:background

fitEnd保留纵横比here

答案 2 :(得分:0)

最后,我使用自定义视图解决了我的问题:

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>