How do I scale a UIButton's imageView?

前端 未结 19 2925
刺人心
刺人心 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 06:02

    Storyboard

    You must define specific property in Runtime Attributes of Identity inspectorimageView.contentModel, where you set value relatively to rawValue position of enum UIViewContentMode. 1 means scaleAspectFit.

    And button's alignment, in Attributes inspector:

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

    Every UIButton has one hidden UIImageView of its own. So we have to set the content mode like the way given below...

    [[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-02 06:05

    An Addition Way for config in XIB file. You can choose this option if you want text or image is Scale full fill in UIButton. It's will be the same with code.

    UIButton *btn = [UIButton new];
    
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    btn.contentVerticalAlignment   = UIControlContentVerticalAlignmentFill;
    

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

    Strange, the only combo that worked for me (iOS 5.1) is...

    button.imageView.contentMode = UIViewContentModeScaleAspectFit;

    and

    [button setImage:newImage forState:UIControlStateNormal];

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

    Just do (From Design OR From Code):

    From Design

    1. Open your xib OR Storyboard.
    2. Select button
    3. Inside Attribute Inspector (Right side) > In "Control" section > select last 4th option for both Horizontal and Verical.

    [For Point#3: Change Horizontal and vertical Align to UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

    From Code

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;
    
    0 讨论(0)
  • 2020-12-02 06:07

    From small test I just did after reading here, depends if you use setImage or setBackgroundImage, both did the same result and strech the image

    //for setBackgroundImage
     self.imageButton.contentMode = UIViewContentModeScaleAspectFill;
            [self.imageButton setBackgroundImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];
    
    //for setImage
     self.imageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
            self.imageButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
        [self.imageButton setImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];
    
    0 讨论(0)
提交回复
热议问题