Home > Software design >  AppCompatImageView displaying big image using ScaleType.CENTER and the use of padding
AppCompatImageView displaying big image using ScaleType.CENTER and the use of padding

Time:12-01

I have an image 3264x1836 and I display it in a custom AppCompatImageView having dimensions 1280x720. I want to preserve the image size so I use ScaleType.CENTER, but I also want that its top-left corner is positioned at the coordinates 0,0 of my custom view, so I set the padding left and top accordingly.
Now, to achieve that I had to use 3264-1280 (the difference between the widths) as left padding and 1836-720 (the difference between the heights) as top padding while, in my opinion, these values should be both divided by 2.
Can somebody explain why?

CodePudding user response:

It is likely that you are breaking the AppCompatImageView code by asking it to do something that wasn't anticipated or tested.

While the above could still be true, the padding that you are applying is correct. Here are the calculations:

For simplicity, let's take a look at the left padding needed to shift the graphic. The same sort of calculations will work for the top padding.

The width of the graphic is greater than the width of the ImageView.

d = wgraphic - wimageview

If the graphic is centered in the ImageView, then the overhang on the left and right sides will be 1/2 the difference in widths.

s = d / 2

The graphic is centered within the padding of the ImageView. The amount of padding that has to be specified must be just enough to shift the center of the graphic by the amount s.

The initial center of the ImageView without padding is

ci = wimageview / 2

The shifted center with left padding ( p ) is

cs = p (wimageview - p) / 2

So,

s = cs - ci = p (wimageview - p) / 2 - (wimageview / 2)

Solving for the padding needed for a shift of s we get p = 2s = d. In other words, the padding we need is twice the shift required which is what you are seeing.

A fix that doesn't involve padding would be to specify

 android:scaleType="matrix" 

You should remove the padding. The new scale type will apply the identity matrix to the image and place it in the top/left corner without resizing.

  • Related