How do I prevent a button's background image from stretching?

后端 未结 10 1818
执笔经年
执笔经年 2021-01-30 16:22

I\'m allocating a UIButtonTypeCustom UIButton to a UIView with a background image that is smaller than the button\'s frame. Reason why the image is smaller is because I\'m tryin

10条回答
  •  生来不讨喜
    2021-01-30 16:51

    You don't have access to the background imageView, but there is fully working workaround:

    EDIT: There is an even better workaround then what I posted originally. You can create a UIImage from any color, and call -setBackgroundImage:forState.

    See bradley's answer, here: https://stackoverflow.com/a/20303841/1147286


    Original answer:

    Instead of calling -setBackgroundImage:forState:, create a new UIImageView and add it as a subview of the button.

    UIImageView *bgImageView = [[UIImageView alloc] initWithImage:img];
    bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    [bgImageView setFrame:CGRectMake(0, 0, videoButton.frame.size.width, videoButton.frame.size.height)];
    bgImageView.tag = 99;
    [yourButton addSubview:bgImageView];
    [yourButton bringSubviewToFront:yourButton.imageView];
    
    1. Create the imageview
    2. Set the content mode and frame
    3. I also set a recognizable tag, so that when the screen rotates I can easily find my custom imageView in the button's subviews and reset its frame
    4. Add it as a subview to the button
    5. Bring the frontal imageView of the button to the front so our custom imageView doesn't overlap it

    When the button needs to rotate just find the imageView by its tag and reset its frame:

    UIImageView *bgImageView = (UIImageView *)[button viewWithTag:99];
    [bgImageView setFrame:CGRectMake(0, 0, newWidth, newHeight)];
    

提交回复
热议问题