【问题标题】:pulling an UIImage from a UITextView or UILabel gives white image从 UITextView 或 UILabel 拉出 UIImage 会给出白色图像
【发布时间】:2011-01-27 11:58:42
【问题描述】:

我需要从 UITextView 或 UILabel 中获取 UIImage。我有一种方法可以成功地从其他类型的视图([UIViewController 视图]、MKMapView、UIButtons)中提取图像,但我的 UITextView 只是得到一个白色矩形。

一段时间以来,我一直在用头撞墙,并怀疑一些非常非常基本的东西。

非常感谢!

@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]];

}

以及来自 UIView 代码的 grabImage

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

    UIGraphicsBeginImageContext(viewToGrab.bounds.size);

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

【问题讨论】:

  • 这是一个 UIImage,而不是 UIImage,因为你将 U 发音为“you”,而不是“ooh-eee-image”。 纳粹>
  • 这就是为什么我做了“一个 UIImage”和“一个 UITextView”。这是一个囚徒困境的答案,我宁愿对一半完全错误......真的,这是故意的......真的。 :)
  • 为了在视网膜显示器上也能获得清晰的图像,我需要将UIGraphicsBeginImageContext(viewToGrab.bounds.size); 替换为:UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);,正如this question 中所要求的那样,并在其接受的答案中进行了解释。也许您可能想更新您的答案,包括该信息。

标签: iphone uiview uiimage uitextview uilabel


【解决方案1】:

技术是正确的。也许是因为文本被翻转了。您可以尝试为坐标系和原点设置变换。就像你通常在绘制文本时所做的那样。

【讨论】:

  • 您好 St3fan,谢谢。我把你说的话放在心上,然后回去检查生成的图像大小和方向,目的是按照你的建议操纵图像。在中间代码重构、笔尖重组和重新启动的某个地方,它开始工作了。我目前的工作理论是我没有正确连接challengeText视图,或者在视图绘制在屏幕上之前调用了图像抓取代码。无论哪种方式,上面的代码似乎确实有效,感谢大家查看它! .
【解决方案2】:

我遇到了同样的问题,得到的是白色矩形而不是文本。为了解决这个问题,我没有使用UIGraphicsBeginImageContext,而是使用UIGraphicsBeginImageContextWithOptions,并为不透明(第二个参数)传递了NO,这样就成功了。

还为比例(第三个参数)传递了 0.0,并获得一个比例因子等于屏幕比例因子的上下文(在我的情况下,在视网膜设备中看起来不错)。

查看有关UIGraphicsBeginImageContextWithOptions here 的Apple 文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多