merging uilabel and uiimageview

2019-08-04 17:28发布

问题:

I picked an image from the photo album and put it in an UIImageView called imageView I then added some text over the image using UITextView as source of input and a UILabel on top of the uiimageview to display the text.

So far so good.

Now I'm trying to merge the label and the imageview in order to do other stuff with that but I 'm not getting it to work. I have tried some solutions given to similar questions but they didn't work for me.

I tried this

UIGraphicsBeginImageContextWithOptions(_imageView.bounds.size, NO, 0.0); //retina res
[self.imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
[_displaylabel.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

it tells me that Received type "CAlayer for instance message is a forward declaration".

any other suggestions?

回答1:

Try this:

UIGraphicsBeginImageContextWithOptions(_imageView.bounds.size, NO, 0.0); //retina res
[self.imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Make sure that the UILabel is a subview of your UIImageView, so that rendering the layer will include all sublayers (the UILabel included). It seems like you forgot to include UIGraphicsEndImageContext(); too, which may have been the issue



回答2:

 UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
 UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imgView.frame.size.width, imgView.frame.size.height)];
    [tempView addSubview:imgView];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(tempView.frame.size.width/2, 0, 200, tempView.frame.size.height/2)];
[label setText:@"Hello... You there"];
[label setTextColor:[UIColor blackColor]];
[label setTextAlignment:NSTextAlignmentLeft];
[label setBackgroundColor:[UIColor clearColor]];
[tempView addSubview:label];


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