3
votes

I have this following codes:

@implementation MyImageView
@synthesize image; //image is a UIImage
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code

}
return self;
}
-(void) removeFromSuperview
{
self.image = nil;
[super removeFromSuperview];
}


- (void)drawRect:(CGRect)rect
{
// Drawing code
if (self.image)
{

    CGContextRef context = UIGraphicsGetCurrentContext();


    CGContextClearRect(context, rect);
    //the below 2 lines is to prove that the alpha channel of my UIImage is indeed drawn
    //CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    //CGContextFillRect(context, rect);
    CGContextDrawImage(context, self.bounds, self.image.CGImage);


}
}
@end

When I ran the code, I realized that the background of my view is black. To test if it was a problem with my UIImage, I used the 2 lines commented after CGContextClearRect(context, rect). Indeed a white background was drawn. Is there anyway for me to remove the black background? When I init MyImageView, i have already set backgroundColor to [UIColor clearColor].

Any advice is much appreciated. Thanks

3
why dont you just uncomment the 2 lines?Omar Abdelhafith
when I uncomment the 2 lines, my background will be white. I need the image's alpha to blend with the backgroundAlexander Lee
oh ok yes you are right now i got itOmar Abdelhafith

3 Answers

4
votes

Setting the background color to [UIColor clearColor] should work. Also set self.opaque = NO to enable transparency.

You should also check that the correct initializer is being called. For example if the view is part of a XIB file, you need to implement initWithCoder: as well as initWithFrame: etc.

2
votes

I had the same issue - this worked for me (Swift example)

    var backgroundImage = UIImage() //background image - size = 100x100
    var frontImage = UIImage()  //smaller image to be drawn in the middle

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), false, 0.0) //false here indicates transparent

    var context = UIGraphicsGetCurrentContext()!

    UIGraphicsPushContext(context)

    backgroundImage.drawInRect(CGRectMake(0, 0, 100, 100))
    frontImage.drawInRect(CGRectMake((100 - frontImage.size.width) / 2, (diameter - frontImage.size.height) / 2, frontImage.size.width, frontImage.size.height))

    UIGraphicsPopContext()

    var outputImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()
0
votes

Your CGContext will draw upside down anyhow, so just go the easy route and use

[self.image drawInRect:CGRectMake(rect)]; 

Instead.