简体   繁体   中英

AttributedString sometimes not successfully drawn using drawInRect

I am having a UILabel with attributed string that user edits and eventually draws on a image. Here's how I update the UILabel every time user changes text in a UITextview and confirm.

 - (void)displayPicture {
    [self.view endEditing:YES];
    self.attributedStr = [[NSAttributedString alloc] initWithString:self.textInputField.text attributes:self.attributes];
    self.displayField.attributedText = [[NSAttributedString alloc] initWithString:self.textInputField.text attributes:self.attributes];
    self.displayField.lineBreakMode = NSLineBreakByCharWrapping;
    [self.displayField sizeToFit];
    [self.displayField setNeedsDisplay];
    self.textInputField.hidden = YES;
    self.tapRecog.enabled = YES;
    self.displayField.hidden = NO;
}

For now the UILabel displays the way desired on the screen.

When user wants the Pic+Text combined to an UIImage and posted, the following code is implemented:

- (UIImage *)generatePicture {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(Picture_Standard_Width, Picutre_Standard_Height), YES, 0.0f);
[self.bgImageView.image drawInRect:CGRectMake(0, 0, Picture_Standard_Width, Picutre_Standard_Height)];
CGRect originalFrame = self.displayField.frame;
CGRect adjustedFrame = CGRectMake(originalFrame.origin.x, originalFrame.origin.y - self.bgImageView.frame.origin.y, originalFrame.size.width, originalFrame.size.height);
[self.displayField.attributedText drawInRect:adjustedFrame];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
self.imageToUpload = newImage;
UIGraphicsEndImageContext();
return self.imageToUpload;
}

Most of the times the attributed only shows one line or two in the generated image. It may very likely have something to do with the frame. I am simply confused by the fact that the attributed string displays nicely in the label and differently when I draw it.

Any help with having the attributedString drawn correctly will be greatly appreciated.

when you start a picture, you start a new context in which you draw.

the Context is the image and 0,0 is the images corner.

so you have to adjust your originalFrame to take into account that you're now no longer drawing into view's context but into the image's context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM