使用矩阵的android缩放图像

时间:2012-03-22 16:51:01

标签: android zoom android-imageview

我在Android中实现缩放图像的代码如下:

public class MyActivity extends Activity{
Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();
    float scaleWidth, scaleHeight,screenWidth,screenHeight;
    ImageView imageView;
@Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Display display = ((WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        screenWidth=display.getWidth();
        screenHeight=display.getHeight();
        imageView = (ImageView) findViewById(R.id.imageview);
        imageView.setScaleType(ScaleType.MATRIX);
        Bitmap cur_bm = BitmapFactory.decodeResource(getResources(),
                R.drawable.myimage);
        float imageWidth = (float) cur_bm.getWidth();
        float imageHeight = (float) cur_bm.getHeight();
        float newHeight = screenHeight;
        float newWidth = screenWidth;
        scaleWidth = screenWidth / imageWidth;
        scaleHeight = newHeight / imageHeight;
        imageView.setImageBitmap(cur_bm);
        SetImageMatrix();
    }

    void SetImageMatrix() {
        Matrix mtrx = new Matrix();
        scaleWidth+=0.6;
        scaleHeight+=0.6;
        mtrx.postScale(scaleWidth, scaleHeight,screenWidth/2, screenHeight/2);
        imageView.setImageMatrix(mtrx);
        imageView.invalidate();
    }
}

如果我对行imageView.setScaleType(ScaleType.MATRIX);发表评论并注释掉函数SetImageMatrix(),那么图像在模拟器中显示如下: enter image description here

但是如果我取消注释行imageView.setScaleType(ScaleType.MATRIX);并保持函数注释,那么图像在模拟器中显示如下:

enter image description here

将scaleType设置为MATRIX会导致图像缩小。有人可以告诉为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

最后,我在其中一篇文章中找到了答案......

Matrix m = imageView.getImageMatrix();

//Get the image's rect
RectF drawableRect = new RectF(0, 0, DrawView.imageWidth.floatValue(),
        DrawView.imageHeight.floatValue());
//Get the image view's rect
RectF viewRect = new RectF(0, 0, imageView.getWidth(),
        imageView.getHeight());
//draw the image in the view
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
//set scale
m.postScale(scaleWidth.floatValue(), scaleHeight.floatValue(), x, y);
imageView.setImageMatrix(m);
imageView.invalidate();