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

后端 未结 10 1836
执笔经年
执笔经年 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:56

    Stumbled on this problem too.

    Adding image programmatically, as memmons thoroughly explained, did not help:(

    I had a button 100x40 and image 100x100, it would appear squeezed, not fitted, as one would infer from "Aspect Fit" option. Actually, non of those view options had an effect.

    I just had to rescale it so it would fit on a button, then use setImage:

    UIImage *img=[UIImage imageNamed:@"myimage.png"];
    CGImageRef imgRef = [img CGImage];
    CGFloat imgW = CGImageGetWidth(imgRef);
    CGFloat imgH = CGImageGetHeight(imgRef);
    CGFloat btnW = myBttn.frame.size.width;
    CGFloat btnH = myBttn.frame.size.height;
    //get lesser button dimension
    CGFloat minBtn=btnW;
    if (btnW>btnH) {
        minBtn=btnH;
    }
    //calculate scale using greater image dimension
    CGFloat scl=imgH/minBtn;
    if (imgW>imgH) {
        scl=imgW/minBtn;
    }
    //scale image
    UIImage *scaledImage = [UIImage imageWithCGImage:[img CGImage] scale:(img.scale * scl) orientation:(img.imageOrientation)];
    //clean up
    UIGraphicsEndImageContext();
    //set it on a button
    [myBttn setImage:scaledImage forState:UIControlStateNormal];
    

提交回复
热议问题