【问题标题】:Crop UIImage with Core Graphics and Layer Mask [duplicate]使用核心图形和图层蒙版裁剪 UIImage [重复]
【发布时间】:2015-04-13 20:56:54
【问题描述】:

我一直在关注这个 SO 问题来裁剪与 IBOutlet 连接的 UIImageView,这是我关注的问题和答案How to crop image inside the circle in UIImageView in iOS。但现在我想知道如何在没有向用户显示 UIImageView 的情况下做到这一点。 (所以没有连接到 IBOutlet)。我在帖子上发表了评论,用户说使用核心图形来裁剪图像而不连接它。我不知道该怎么做?所以我想知道如何将裁剪应用于具有核心核心图形的 UIImage 或 UIImageView?

提前感谢您的帮助。

【问题讨论】:

    标签: ios objective-c uiimageview uiimage


    【解决方案1】:

    例如,您可以执行以下操作,创建位图上下文,添加剪切路径,将图像绘制到该上下文中,然后将图像从该上下文中提取出来:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    size_t width = image.size.width, height = image.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = (CGBitmapInfo)kCGImageAlphaPremultipliedLast;
    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 4 * width, colorSpace, bitmapInfo);
    
    CGRect rect = ...
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);
    
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *final = [UIImage imageWithCGImage:imageRef];
    
    NSData *data = UIImagePNGRepresentation(final);
    
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *savePath      = [documentsPath stringByAppendingPathComponent:@"final.png"];
    
    [data writeToFile:savePath atomically:YES];
    
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    CGContextRelease(context);
    

    有关详细信息,请参阅Quartz 2D Programming Guide。或参考CGContext Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 2010-11-03
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多