Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine UIImage and UILabel into one image and save

I have 2 UILabels and 2 images that i need to merge into a single UIImage to save.

I know I could do it with screen shots but my main image is rounded so if I rect it, it will still show the sharp edge.

I can do this to combine the images :

//CGSize newImageSize = CGSizeMake(cropImage.frame.size.width, cropImage.frame.size.height);
CGSize newImageSize = CGSizeMake(480, 320);
NSLog(@"CGSize %@",NSStringFromCGSize(newImageSize));

UIGraphicsBeginImageContextWithOptions(newImageSize, NO, 0.0); //retina res
[self.viewForImg.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

NSData *imgData =  UIImageJPEGRepresentation(image, 0.9); //UIImagePNGRepresentation ( image ); // get JPEG representation
UIImage * imagePNG = [UIImage imageWithData:imgData]; // wrap UIImage around PNG representation

UIGraphicsEndImageContext();
return imagePNG;

but not sure how to add in the UILabel.

Any reply is much appreciated.

like image 687
Desmond Avatar asked Nov 23 '12 02:11

Desmond


People also ask

How do I add an image to UIImage?

With Interface Builder it's pretty easy to add and configure a UIImageView. The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project).

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage . Save this answer.

How do you add a UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in . h file and allocated in init method, I need to set image in viewDidLoad method.


1 Answers

Use [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()]; to draw in current context.

For eg:-

    UIGraphicsBeginImageContextWithOptions(newImageSize, NO, 0.0); //retina res
    [self.viewForImg.layer renderInContext:UIGraphicsGetCurrentContext()];
    [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

Based on your comments, if you want to draw this in a particular frame do it as follows,

[myLabel drawTextInRect:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];

If you want to color the background, try this,

CGRect drawRect = CGRectMake(rect.origin.x, rect.origin.y,rect.size.width, rect.size.height); 
CGContextSetRGBFillColor(context, 100.0f/255.0f, 100.0f/255.0f, 100.0f/255.0f, 1.0f); 
CGContextFillRect(context, drawRect);

or you can check this question Setting A CGContext Transparent Background.

like image 100
iDev Avatar answered Oct 29 '22 04:10

iDev