开发者

How to make UIButton use a masked image correctly?

I’m creating a UIButton programmatically and then adding a masked image with setImage:

CGRect photoFrame = CGRectMake(11, 11, 180, 120)开发者_开发百科;
UIButton *cardPhotoButton = [[UIButton alloc] initWithFrame:photoFrame];
cardPhotoButton.backgroundColor = [UIColor clearColor];

UIImage *cardPhoto = [[UIImage alloc] init];
cardPhoto = [self maskImage:
[UIImage imageNamed:[metaDict objectForKey:@"Photo"]] withMask:[UIImage imageNamed:@"CardPhotoFrame.png"]];

[cardPhotoButton setImage:cardPhoto forState:UIControlStateNormal];

cardPhotoButton.contentMode = UIViewContentModeScaleAspectFit;

[self addSubview:cardPhotoButton];

The masking is done with this method I got from the web:

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    return [UIImage imageWithCGImage:masked];
}

Now, the problem is that the masking for the default state does not work, but weirdly when I actually click on the button and the button goes to "highlighted" state, the transparent parts of the masked image start to work.

I’m guessing I need to set somekind of BG color to clearColor somewhere, but I’ve tried them all and none work.

Any ideas what I might be missing?


what is your actual requirement? you want different images for normal and highlighted state or the image size is not properly fitting the button?

If the issue is of image not fitting properly then the reason is you need to set type of the button as custom type.


you can use : OBShapedButton, https://github.com/ole/OBShapedButton

OBShapedButton is a UIButton subclass optimized for non-rectangular button shapes. Instances of OBShapedButton respond to touches only in areas where the image that is assigned to the button for UIControlStateNormal is non-transparent.

I got this answer from this question: How Do I Create a Circular UIButton?

it worked perfectly for me :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜