Friday, 25 December 2009

Android: How to scale an image in ImageView

To scale an image in the provided ImageView control, use this basic code:


Matrix mtrx = new Matrix;
mtrx.postScale(scalefactorX, scalefactorY);
mtrx.postTranslate(offsetX, offsetY);
pic.setImageMatrix(mtrx);
pic.setScaleType(ScaleType.MATRIX);
pic.invalidate();


This will increase the image size by scalefactorX and scalefactorY, and move the image so that the top left corner is at the location specified by offsetX and offsetY.

1 comment:

Ian said...

Hi

I tried this when clicking a zoom button but it had no effect whatsoever.

Any ideas?

Cheers,
Ian.

My code is almost identical:-

ImageView bgnd = (ImageView) findViewById(R.id.imgMap);
Matrix mtrx = new Matrix();
mtrx.postScale(_scaling, _scaling);
mtrx.postTranslate(_canvasXOffset, _canvasYOffset);
bgnd.setImageMatrix(mtrx);
bgnd.setScaleType(ScaleType.MATRIX);
bgnd.invalidate();