Reputation: 4595
I need to scale an Image inside an ImageView, I need to use the matrix for doing so,
So I do;
private void scaleImage(float scaleFactor, float focusX,float focusY) {
Matrix displayMatrix= new Matrix();
matrix.postScale(scaleFactor, scaleFactor);
displayMatrix.set(matrix);
imageView.setImageMatrix(displayMatrix);
}
The problem is no matter what i am not able to center the image inside the ImageView,
I need to put the image at the center (leaving white margins if the image is smaller than the view)
I have been bangin my head for hours, please help.
I have looked extensively at this https://stackoverflow.com/a/6172226/1815311, but without success.
Upvotes: 0
Views: 3456
Reputation: 1691
All you have to do is to find new x and y coordinates where to place the image and then translate the matrix, so the image moves to the center of the ImageView. Your entire scaleImage method can look something like this:
private void scaleImage(float scaleFactor, float focusX, float focusY) {
Matrix displayMatrix = new Matrix();
Matrix matrix = imageView.getImageMatrix();
float x = (imageView.getWidth() - imageView.getDrawable().getIntrinsicWidth() * scaleFactor) / 2;
float y = (imageView.getHeight() - imageView.getDrawable().getIntrinsicHeight() * scaleFactor) / 2;
matrix.postScale(scaleFactor, scaleFactor);
matrix.postTranslate(x, y);
displayMatrix.set(matrix);
imageView.setImageMatrix(displayMatrix);
}
Upvotes: 2
Reputation: 2007
Try my code hope will help you:
private void scaleImage(ImageView view, int boundBoxInDp)
{
// Get the ImageView and its bitmap
Drawable drawing = view.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) boundBoxInDp) / width;
float yScale = ((float) boundBoxInDp) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params (LinearLayout.LayoutParams)view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
Upvotes: 0