裁剪六角形的UIImage?

Nat*_*kel 2 crop uiimage ios

所以我已经看到了如何将UIImages裁剪成某些形状的解决方案,但是六边形呢?

一个想法:子类UIImage,改变drawRect方法只绘制某些部分?

编辑:更具体一点,我希望保持图像边界相同,但使六边形外的图像数据透明,所以看起来图像是六边形的形状,实际上它有相同的矩形边界,只有部分图像是透明的.

不确定.很想听听你们的想法.

Zev*_*erg 10

你能把图像放在一个UIImageView?如果是这样:

创建一个新的CAShapeLayer(记得导入QuartzCore!).创建一个CGPathRefUIBezierPath六边形,并将其设置为形状图层的path属性.将形状图层设置为mask图像视图图层的形状图层.

如果要修改UIImage自身,可能需要添加一个类别方法- (UIImage)hexagonImage,将图像绘制为CGGraphicsContext使用六边形路径剪切的图像CGContextClipPath,然后返回UIImage从图形上下文创建的图像.

编辑:这是代码示例

(注意:在构建我的答案时我有点遗憾,除了在ZEPolygon的示例项目中生成UIBezierPath n字符的一些代码之外,您还可以看到下面提到的两种技术)

方法1:使用屏蔽图像视图 CAShapeLayer

UIImageView *maskedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];

// insert your code for generating a hexagon here, or use mine from ZEPolygon
UIBezierPath *nonagon = [UIBezierPath bezierPathWithPolygonInRect:maskedImageView.frame numberOfSides:9];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = nonagon.CGPath;

maskedImageView.layer.mask = shapeLayer;

[self.view addSubview:maskedImageView];
Run Code Online (Sandbox Code Playgroud)

方法2:类别打开UIImage以返回屏蔽版本

UIImage+PolygonMasking.h:

#import <UIKit/UIKit.h>

@interface UIImage (ABCPolygonMasking)

- (UIImage *)abc_imageMaskedWithPolygonWithNumberOfSides:(NSUInteger)numberOfSides;

@end
Run Code Online (Sandbox Code Playgroud)

UIImage+PolygonMasking.m:

#import "UIImage+PolygonMasking.h"
#import "UIBezierPath+ZEPolygon.h"

@implementation UIImage (ABCPolygonMasking)

- (UIImage *)abc_imageMaskedWithPolygonWithNumberOfSides:(NSUInteger)numberOfSides
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // insert your code for generating a hexagon here, or use mine from ZEPolygon
    UIBezierPath *path = [UIBezierPath bezierPathWithPolygonInRect:CGRectMake(0, 0, self.size.width, self.size.height)
                                                     numberOfSides:numberOfSides];

    CGContextSaveGState(ctx);
    [path addClip];
    [self drawAtPoint:CGPointMake(0, 0)];
    CGContextRestoreGState(ctx);

    UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return retImage;
}

@end
Run Code Online (Sandbox Code Playgroud)