pulling an UIImage from a UITextView or UILabel gi

2019-03-20 15:40发布

I need to grab an UIImage from a UITextView or UILabel. I've got a method that will pull an image successfully from other types of views ( [UIViewController view], MKMapView, UIButtons) but I am just getting a white rect for my UITextView.

I've been banging my head against the wall for a while and suspect something really, really basic.

many thanks!

@interface TaskAccomplishmentViewController : UIViewController {

    MKMapView *mapView;
    UILabel *timeLeftText;
    UITextView *challengeText;

    UIButton *successButton;

<snip>

- (void) setChallangeImageToImageFromChallenge {

    // works
    // [currChallenge setChallengeImage:[UIImageUtils grabImageFromView:mapView]];
    // [currChallenge setChallengeImage:[UIImageUtils grabImageFromView:[self view]]];
    // [currChallenge setChallengeImage:[UIImageUtils grabImageFromView:successButton]];

    // doesn't work
    // [currChallenge setChallengeImage:[UIImageUtils grabImageFromView:timeLeftText]];
    [currChallenge setChallengeImage:[UIImageUtils grabImageFromView:challengeText]];

}

and the grabImage from a UIView code

+(UIImage *)grabImageFromView: (UIView *) viewToGrab {

    UIGraphicsBeginImageContext(viewToGrab.bounds.size);

    [[viewToGrab layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

2条回答
小情绪 Triste *
2楼-- · 2019-03-20 16:12

I was having the same problem, getting a white rect instead of the text. To solve this, instead of using UIGraphicsBeginImageContext I used UIGraphicsBeginImageContextWithOptions and passed NO for opaque (second argument), that did the trick.

Also passed 0.0 for scale (third argument) and to get a context with a scale factor equal to that of the screen (to look good in retina device in my case).

Check the Apple doc about UIGraphicsBeginImageContextWithOptions here.

查看更多
冷血范
3楼-- · 2019-03-20 16:15

The technique is correct. Maybe it is because text is flipped. You could try to set a transform for the coordinate system and origin. Like you would normally do when drawing text.

查看更多
登录 后发表回答