How do I scale a UIButton's imageView?

前端 未结 19 2927
刺人心
刺人心 2020-12-02 05:16

I created a UIButton instance named \"button\" with an image using [UIButton setImage:forState:]. The button.frame is larger than the image\'s size.

Now

相关标签:
19条回答
  • 2020-12-02 05:55

    At the bottom left of screenshot, you can see Stretching properties. Try using those.

    0 讨论(0)
  • 2020-12-02 05:56

    For the original poster, here is the solution I found:

    commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    

    This will allow your button to scale horizontally. There is a vertical setting as well.

    Took me several hours to figure that one out (the naming of the property is very unintuitive) so figured I'd share.

    0 讨论(0)
  • 2020-12-02 05:58

    I just ran into this same problem, and there's a possible answer in this question:

    Why does a custom UIButton image does not resize in Interface Builder?

    Essentially, use the backgroundimage property instead, which does get scaled.

    0 讨论(0)
  • 2020-12-02 05:58

    like this can solve your problem:

    + (UIImage*)resizedImage:(UIImage*)image
    {
     CGRect frame = CGRectMake(0, 0, 60, 60);
     UIGraphicsBeginImageContext(frame.size);
     [image drawInRect:frame];
     UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
    
     return resizedImage;
    }
    
    0 讨论(0)
  • 2020-12-02 06:00

    I'd faced similar problem, where I've a background Image (one with border) and an image (flag) for a custom button. I wanted flag to be scaled down and in center. I tried changing imageView's attribute but didn't succeed and was seeing this image --

    enter image description here

    During my experiments, I tried :

    button.imageEdgeInsets = UIEdgeInsetsMake(kTop,kLeft,kBottom,kRight)
    

    I achieved expected result as :

    enter image description here

    0 讨论(0)
  • 2020-12-02 06:01

    I hope this can help to somebody else:

    Swift 3+

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.fill
    button.contentVerticalAlignment =  UIControlContentVerticalAlignment.fill
    
    0 讨论(0)
提交回复
热议问题