sdknewbie
sdknewbie

Reputation: 669

How do I save a photo with a label overlaid on the photo?

So I have data I want to overlay on a photo when it is taken. Here is my code. Is there an easier way to overlay data on photos?

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info 
{         
    UIImage *cameraImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageView *imageViewToSave = [[UIImageView alloc] initWithImage:cameraImage];
    CGRect textFrame = CGRectMake(0, 0, imageViewToSave.frame.size.width-20, 325);
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:textFrame];
    tempLabel.text = self.temperatureText.text;
    tempLabel.font = self.imageLabelFont;
    tempLabel.adjustsFontSizeToFitWidth = YES;
    tempLabel.textAlignment = NSTextAlignmentRight;
    tempLabel.textColor = self.tempGreen;
    tempLabel.backgroundColor = [UIColor clearColor];
    [imageViewToSave addSubview:tempLabel];

    UIGraphicsBeginImageContext(imageViewToSave.bounds.size);
    [imageViewToSave.layer renderInContext:UIGraphicsGetCurrentContext()];

    cameraImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self.library saveImage:cameraImage toAlbum:@"Node Therma" withCompletionBlock:^(NSError *error) 
    {
        if (error!=nil) 
        {
            NSLog(@"Big error: %@", [error description]);
        }
    }];

}

Upvotes: 0

Views: 151

Answers (2)

nzs
nzs

Reputation: 3252

Your code seems ok, compared to mine which works fine, but try using a new local variable when getting the screenshot, like this:

UIImage *cameraImage2 = UIGraphicsGetImageFromCurrentImageContext();

then save cameraImage2.

Also make sure that self.tempGreen is not ClearColor.

Upvotes: 0

danh
danh

Reputation: 62686

Just tested this, and it works ...

- (UIImage *)imageWithBackground:(UIImage *)background text:(NSString *)text textColor:(UIColor *)textColor {

    UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
    UIView *composition = [[UIView alloc] initWithFrame:imageView.bounds];
    [composition addSubview:imageView];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/* where you want the label */)];
    label.text = text;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = textColor;
    [composition addSubview:label];

    UIGraphicsBeginImageContext(composition.bounds.size);
    [composition.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *composedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return composedImage;
}

Upvotes: 1

Related Questions