I am trying to manually get an image inside an imageview centered and fitting the screen. I need to do it with a matrix (I will later dynamically change the matrix transformation).
Problem is I can't get the image centered in the view (scale is appropriate). Here is the code:
// Compute the scale to choose (this works) float scaleX = (float) displayWidth / (float) imageWidth; float scaleY = (float) displayHeight / (float) imageHeight; float minScale = Math.min(scaleX, scaleY); // tx, ty should be the translation to take the image back to the screen center float tx = Math.max(0, 0.5f * ((float) displayWidth - (minScale * imageWidth))); float ty = Math.max(0, 0.5f * ((float) displayHeight - (minScale * imageHeight))); // Compute the matrix Matrix m = new Matrix(); m.reset(); // Middle of the image should be the scale pivot m.postScale(minScale, imageWidth/2, imageHeight/2); // Translate m.postTranslate(tx, ty); imageView.setImageMatrix(m);
The above code works if I don't center the scale on the image center (but I will need to do it later so I need to figure out the formula now).
I thought doing the following would correct the issue, but the image is still offset (towards bottom and right).
tx += 0.5*imageWidth*minScale; ty += 0.5*imageHeight*minScale;
Some values I have: - image: 200x133 - display: 800x480 - minScale: 2.4 - final top-left corner of the image: 100, 67 (should be 17, 0)
The matrix supports a bunch of different transformations like translate , scale , rotate and skew . If those sound familiar it's because they're (mostly) the same as on a view, an animation or the canvas.
ImageView class is used to display any kind of image resource in the android application either it can be android. graphics. Bitmap or android. graphics. drawable.
There's a convenient method called Matrix.setRectToRect(RectF, RectF, ScaleToFit) to help you here.
Matrix m = imageView.getImageMatrix(); RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight); RectF viewRect = new RectF(0, 0, imageView.getWidth(), imageView.getHeight()); m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER); imageView.setImageMatrix(m);
That should set the matrix m
to have combo of scaling and translate values that is needed to show the drawable centered and fit within the ImageView widget.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With