Search code examples
androidviewscale

Android: Manually Scaling a View


Is there a way to manually scale a view while making sure the position translates properly? The only way I can scale it right now is to update the LayoutParams by essentially multiplying the width and height my a scale factor. This works okay but I'm not sure about how to translate the position properly. Further, I want to scale the view with the pivot being the center as well. I'm actually able to perform the behavior I want with by using the ScaleAnimation like so,

ScaleAnimation anim = new ScaleAnimation(fromX, toX,
                fromY, toY, ScaleAnimation.RELATIVE_TO_SELF,
                0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f);

However, the actual view's bounds are not adjusted. The majority of scaling implementations and help always deal with an ImageView so I figured it's worth asking for a View only. I'd be greatly appreciative if any has any ideas on this matter.


Solution

  • It sounds like you want to scale a View, but scale it from the center of the View. This is tricky because the View is positioned based on it's top and left offset from the top left corner of it's parent.

    So -- if you have a view that is 100px from the top, and 100px from the left, and the size is 50px by 50px - and you want to scale it by +10%:

    width = 50px * 1.1 = 55px;
    height = 50px * 1.1 = 55px;
    

    but those extra 5px will be added to the right and bottom of the View, right? so we need to change the offset of the View to adjust:

    top = 100px - ((100px * .1) / 2) = 97.5px
    

    (same for the left, obviously).

    using this pattern, you can scale the view in a way that keeps the center point consistent.