我试图在iPhone上编写动画,但遇到了很多问题,程序崩溃,什么都不起作用。
我想要做的看起来很简单,创建一个UIImage,然后将另一个UIImage的一部分绘制到其中,但我对上下文和层等内容感到有些困惑。
请问有人可以解释如何编写这样的内容(高效)并提供示例代码吗?
我试图在iPhone上编写动画,但遇到了很多问题,程序崩溃,什么都不起作用。
我想要做的看起来很简单,创建一个UIImage,然后将另一个UIImage的一部分绘制到其中,但我对上下文和层等内容感到有些困惑。
请问有人可以解释如何编写这样的内容(高效)并提供示例代码吗?
记录一下,这实际上非常简单——你需要了解的所有内容都在以下示例中:
+ (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;
}
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
。 - Daij-Djan我想就dpjanes上面的答案添加一条评论,因为这是一个很好的答案,但在iPhone 4上(具有高分辨率视网膜显示屏)会显得有点方块化,因为“UIGraphicsGetImageFromCurrentImageContext()”无法以iPhone 4的全分辨率呈现。
使用“...WithOptions()”代替。但是由于WithOptions直到iOS 4.0才可用,您可以进行弱链接(讨论请参见此处),然后使用以下代码仅在支持高分辨率版本时使用:
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
}
else {
UIGraphicsBeginImageContext();
}
以下是将两个大小相同的图像合并成一个的示例。我不知道这是否是最好的方法,也不知道类似的代码是否已经发布在其他地方。这里是我的建议。
+ (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;
}