在另一张UIImage的顶部添加UIImage

12

我有2个图片:第一个是用户个人照片,第二个是图标(徽章)。

我想将第二个UIImage(图标)添加到第一个UIImage(用户的照片)的左下角,并将它们保存为新的UIImage。

谢谢

2个回答

28

尝试使用这种方法:

-(UIImage *)drawImage:(UIImage*)profileImage withBadge:(UIImage *)badge
{
    UIGraphicsBeginImageContextWithOptions(profileImage.size, NO, 0.0f);
    [profileImage drawInRect:CGRectMake(0, 0, profileImage.size.width, profileImage.size.height)];
    [badge drawInRect:CGRectMake(0, profileImage.size.height - badge.size.height, badge.size.width, badge.size.height)];
     UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return resultImage;
}

你可以通过以下方式使用它:

UIImage *myBadgedImage = [self drawImage:profileImage withBadge:badgeImage];

有没有想法为什么代码会选择某些UIImages并放大它们 - 实际上失去了实际大小?对我们来说,这段代码不起作用,因为我们的图像被放大了 - 即使我们只传递没有徽章的个人资料图像。 - Praxiteles
挽救了我的一天。虽然我希望不必使用这个辅助工具,而是将UIImageView堆叠在一起。 - Anton Tropashko
@AntonTropashkobadge.size.height 在不同的图像上会有所变化,即徽章图像会被调整大小。我们能否使其适应任何 profileImage 大小(比如说高度为 100)?谢谢! - Gopik

2

试试这个:

CGFloat scale = [self currentScale];
if (scale > 1.5)
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, scale);
else
    UIGraphicsBeginImageContext(view.frame.size);

[image1 drawInRect:CGRectMake(0, 0, w1, h1)];
[image2 drawInRect:CGRectMake(0, 0, w2, h2)];

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接