views:

53

answers:

1

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?

A: 

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.

Javal Nanda
I want all states to have the same image, but I need the image mask to work and currently the image transparency is not showing up in the Default state, only in the HighLighted state.
margusholland
Is there any specific need of masking? If you want the same image i.e you want to make button appear as dimension of ur image then just set the button type to custom and set the image for normal ,highlighted and selected state. so the image will remain the same in all the cases.hope now its possible for u to find the solution.
Javal Nanda
The image is actually a photo that I want to add a mask that will make the photo have a specific frame I’m trying to add. And creating a new UIButton my default makes it a UIButtonTypeCustom doesn’t it?
margusholland