在另一个图像上绘制圆形图像 - UIGraphicsBeginImageContextWithOptions

时间:2014-03-13 17:52:36

标签: ios uiimageview uiimage uigraphicscontext

我一直在努力研究这种方法。我正在另一个图像上绘制一个头像。用户图片我想成为一个圆圈,但我似乎无法弄清楚如何。用户图片为UIImage,而非UIImageView。如果它是一个imageview,我知道如何制作一个圆圈。下面是代码。可能有更好的方法。

-(UIImage *)drawImage:(UIImage*)pinImage withBadge:(UIImage *)user{



    UIGraphicsBeginImageContextWithOptions(pinImage.size, NO, 0.0f);
    [pinImage drawInRect:CGRectMake(0, 0, pinImage.size.width, pinImage.size.height)];
    [user drawInRect:CGRectMake(20.0, 10.0, user.size.width/2, user.size.height/2)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resultImage;

}

结果很好,但用户图像仍为方形,不是圆形。我尝试将用户图片添加到UIImageView,将其转换为圆圈,然后通过调用yourImageView.image在方法中使用它,但没有运气。我还尝试了很多其他方法。我的逻辑很可能不正确。

期望的结果是在图钉/注释之上的圆形图像位置。黑点是一个图像(比这个更大的圆圈)。

enter image description here

2 个答案:

答案 0 :(得分:3)

您可以将图像上下文剪切到图像的路径

// Start the image context
UIGraphicsBeginImageContextWithOptions(pinImage.size, NO, 0.0);
UIImage *resultImage = nil;

// Get the graphics context
CGContextRef context = UIGraphicsGetCurrentContext();

// Draw the first image
[pinImage drawInRect:CGRectMake(0, 0, pinImage.size.width, pinImage.size.height)];

// Get the frame of the second image
CGRect rect = CGRectMake(20.0, 10.0, user.size.width/2, user.size.height/2)

// Add the path of an ellipse to the context
// If the rect is a square the shape will be a circle
CGContextAddEllipseInRect(context, rect);
// Clip the context to that path
CGContextClip(context);

// Do the second image which will be clipped to that circle
[user drawInRect:rect];

// Get the result
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); 

// End the image context
UIGraphicsEndImageContext();

答案 1 :(得分:0)

创建一个圆形路径,然后剪切到那个?

CGContextAddArc(ctx, ....);
CGContextClip(ctx);
相关问题