自动位图拉伸以适合ImageView

时间:2013-07-22 18:24:47

标签: java android bitmap imageview scale

我有一个80dp * 80dp的位图。 ImageView大小会自动缩放 ImageView大小为:130DP * 130DP(大于位图大小)。

我试图将位图放入imageView大小(我不介意丢失图像质量)。

以下是一些代码:

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

   <com.inturnex.safecam.SquareImageView 
       android:id="@+id/imageView" 
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:src="@drawable/locked_image"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    />


</LinearLayout>

我以编程方式设置位图。 ImageView的大小为130DP,但我看到的图像大小为80DP(作为原始位图,它不会伸展以适合ImageView大小)。

为了完成这项任务,我该怎么办?谢谢!

编辑: SquareImageView实施:

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

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

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

1 个答案:

答案 0 :(得分:0)

您可能会尝试使用缩放到Matrix(以编程方式或以xml格式)

imageView.setScaleType(ScaleType.MATRIX);
Matrix matrix = new Matrix();
matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.FILL);
imageView.setBitmap(bitmap);

在这里,Dalvik拍摄您的图像,应用缩放矩阵,使其填充您的ImageView。您的drawableRect应包含Bitmap的尺寸,viewRect,imageView的尺寸。