【问题标题】:Create a UIImage from two other UIImages on the iPhone从 iPhone 上的其他两个 UIImage 创建一个 UIImage
【发布时间】:2009-03-24 21:08:22
【问题描述】:

我正在尝试在 iPhone 上编写动画,但没有取得多大成功,出现崩溃,似乎没有任何效果。

我想做的事情看起来很简单,创建一个 UIImage,然后将另一个 UIImage 的一部分绘制到其中,我对上下文、图层和其他东西有点困惑。

有人可以用示例代码解释一下如何(有效地)编写类似的东西吗?

【问题讨论】:

  • 您真的想要一个新的 UIImage(例如,您可以将其保存到磁盘或通过网络发送)还是只想在屏幕上叠加两个 UIImage,一个在另一个之上?跨度>
  • 我建议买一本好的入门书。我目前正在阅读这篇文章:iphonedevbook.com 它有关于绘图和动画等的章节。
  • 我想要一个实际的 UIImage,所以我可以在动画中使用它。我阅读了一些文档,但它们都显示了如何绘制框和线,而不是更复杂的实际图片。

标签: iphone uiimage


【解决方案1】:

为了记录,事实证明这相当简单 - 您需要知道的一切都在下面的示例中:

+ (UIImage*) addStarToThumb:(UIImage*)thumb
{
   CGSize size = CGSizeMake(50, 50);
   UIGraphicsBeginImageContext(size);

   CGPoint thumbPoint = CGPointMake(0, 25 - thumb.size.height / 2);
   [thumb drawAtPoint:thumbPoint];

   UIImage* starred = [UIImage imageNamed:@"starred.png"];

   CGPoint starredPoint = CGPointMake(0, 0);
   [starred drawAtPoint:starredPoint];

   UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return result;
}

【讨论】:

  • 在retina display中,结果图像的质量很差。
  • 对于视网膜模式,使用UIGraphicsBeginImageContextWithOptions(size, NO, 0);
【解决方案2】:

我只想对 dpjanes 的上述答案添加评论,因为它是一个很好的答案,但在 iPhone 4(具有高分辨率视网膜显示器)上会显得块状,因为“UIGraphicsGetImageFromCurrentImageContext()”不会完全呈现iPhone 4 的分辨率。

请改用“...WithOptions()”。但是由于 WithOptions 在 iOS 4.0 之前不可用,您可以对其进行弱链接 (discussed here),然后使用以下代码仅在支持的情况下使用雇用版本:

if (UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
}
else {
    UIGraphicsBeginImageContext();
}

【讨论】:

    【解决方案3】:

    这是一个将两个相同大小的图像合并为一个的示例。我不知道这是否是最好的,也不知道这种代码是否发布在其他地方。这是我的两分钱。

    + (UIImage *)mergeBackImage:(UIImage *)backImage withFrontImage:(UIImage *)frontImage
    {
    
        UIImage *newImage;
    
        CGRect rect = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    
        // Begin context
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    
        // draw images
        [backImage drawInRect:rect];
        [frontImage drawInRect:rect];
    
        // grab context
        newImage = UIGraphicsGetImageFromCurrentImageContext();
    
        // end context
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      相关资源
      最近更新 更多