在ImageView android中居中和缩放图像

时间:2015-03-15 15:00:03

标签: java android xml image imageview

我有方形图像,需要它们放大以填充视图,同时位于中心。

我已经尝试了所有的XML选项而没有任何变化 - 当我在纵向和横向模式之间切换方向时,图像总是填充视图并延伸。

我现在已经实现了一个自定义ImageView来覆盖onMeasure方法,并根据屏幕大小设置Drawable图像尺寸。但我有同样的问题 - 图像仍然在纵向和横向模式下延伸。

以下是代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.mypackage.BackgroundImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/backgroundImage"/>
    ...

自定义ImageView类:

public class BackgroundImageView extends ImageView {

    public BackgroundImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final Drawable drawable = this.getDrawable();
        if (drawable != null) {
            float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
            float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
            if (imageSideRatio >= viewSideRatio) {
                // Image is wider than the display (ratio)
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = (int)(width / imageSideRatio);
                setMeasuredDimension(width, height);
            } else {
                // Image is taller than the display (ratio)
                int height = MeasureSpec.getSize(heightMeasureSpec);
                int width = (int)(height * imageSideRatio);
                setMeasuredDimension(width, height);
            }
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

}

如何防止图像拉伸,而是让图像溢出图像视图(或裁剪图像)?

0 个答案:

没有答案
相关问题