Search Unity

Clamping a ui image to a mask region

Discussion in 'Scripting' started by Kellyrayj, Jul 26, 2016.

  1. Kellyrayj

    Kellyrayj

    Joined:
    Aug 29, 2011
    Posts:
    936
    Hey friends,

    Working on a problem that involves dragging a UI image around a masked screen area. I'd like to limit the ability of a user to drag the image past the mask so the top of the image will never be below the top of the mask. This would be true for the bottom, left and right sides of the mask as well.

    Hoping these demonstrate what I intend to accomplish:
    Screen Shot 2016-07-26 at 12.48.35 PM.png
    Clamping to the top:
    Screen Shot 2016-07-26 at 12.48.45 PM.png
    Clamping to the right:

    Screen Shot 2016-07-26 at 12.48.52 PM.png

    Any thoughts on how I might go about this?
     
  2. Kellyrayj

    Kellyrayj

    Joined:
    Aug 29, 2011
    Posts:
    936
    Solved it!

    For anyone who is interesting here's the code.

    PhotoMinWidth is the mask Rect Transform.

    Code (CSharp):
    1.     public void ClampScaleX(){
    2.  
    3.         photoRect.localScale = new Vector3 (PhotoMinWidth.sizeDelta.x / photoRect.sizeDelta.x, PhotoMinWidth.sizeDelta.x / photoRect.sizeDelta.x, PhotoMinWidth.sizeDelta.x / photoRect.sizeDelta.x);
    4.    
    5.     }
    6.  
    7.     public void ClampScaleY(){
    8.  
    9.         photoRect.localScale = new Vector3 (PhotoMinWidth.sizeDelta.y / photoRect.sizeDelta.y, PhotoMinWidth.sizeDelta.y / photoRect.sizeDelta.y, PhotoMinWidth.sizeDelta.y / photoRect.sizeDelta.y);
    10.  
    11.     }
    12.  
    13.     public void ClampRight(){
    14.  
    15.         float picClampPosRight = ((photoRect.sizeDelta.x * photoRect.localScale.x) - PhotoMinWidth.sizeDelta.x)/2f;
    16.         photoRect.anchoredPosition = new Vector2 (-picClampPosRight, photoRect.anchoredPosition.y);
    17.    
    18.     }
    19.  
    20.     public void ClampLeft(){
    21.  
    22.         float picClampPosLeft = ((photoRect.sizeDelta.x * photoRect.localScale.x) - PhotoMinWidth.sizeDelta.x)/2f;
    23.         photoRect.anchoredPosition = new Vector2 (picClampPosLeft, photoRect.anchoredPosition.y);
    24.  
    25.     }
    26.  
    27.     public void ClampTop(){
    28.  
    29.         float picClampPosTop = ((photoRect.sizeDelta.y * photoRect.localScale.y) - PhotoMinWidth.sizeDelta.y)/2f;
    30.         photoRect.anchoredPosition = new Vector2 (photoRect.anchoredPosition.x, - picClampPosTop);
    31.  
    32.     }
    33.  
    34.     public void ClampBottom(){
    35.  
    36.         float picClampPosBtm = ((photoRect.sizeDelta.y * photoRect.localScale.y) - PhotoMinWidth.sizeDelta.y)/2f;
    37.         photoRect.anchoredPosition = new Vector2 (photoRect.anchoredPosition.x, picClampPosBtm);
    38.  
    39.     }
     
    LeftyRighty likes this.