floxxxy floxxxy - 4 months ago 44
iOS Question

UIGraphicsGetImageFromCurrentImageContext - Split image into two creates a black background

I would like to split a UIImage into two single images.
I use the following (working) code.

UIImage *splitMeInTwo = [UIImage imageNamed:@"Star.png"];

UIImageView *original = [[UIImageView alloc] initWithImage:splitMeInTwo];
[self.view addSubview:original];
[original release];

// The size of each part is half the height of the whole image
CGSize size = CGSizeMake([splitMeInTwo size].width, [splitMeInTwo size].height/2);

// Create image-based graphics context for top half
UIGraphicsBeginImageContextWithOptions(size, TRUE, 0.0);

// Draw into context, bottom half is cropped off
//[image drawAtPoint:CGPointMake(0.0,0.0)];
[splitMeInTwo drawAtPoint:CGPointMake(0.0,0.0) blendMode:kCGBlendModeNormal alpha:1.0];

// Grab the current contents of the context as a UIImage
// and add it to our array
UIImage *top = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *topV = [[UIImageView alloc] initWithImage:top];
CGRect frameTop = topV.frame;
frameTop.origin.x += 360.0f;
topV.frame = frameTop;
[self.view addSubview:topV];
[topV release];


=> The result

This code works well but the UIImage I get from "UIGraphicsGetImageFromCurrentImageContext" has always a black background.

How can I split the "splitMeInTwo"-UIIMage and keep the transparent background?

Thank you!

UPDATE: Image link is now working, sorry ;)


Try setting the opaque parameter to NO.

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);