裁剪六角形的UIImage?

时间:2013-07-27 04:35:57

标签: ios uiimage crop

所以我看到了如何将UIImage裁剪成某些形状的解决方案,但是六边形怎么样?

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

编辑:更具体一点,我希望保持图像边界相同,但是使六边形外的图像数据透明,因此出现图像的形状为六角形,实际上它具有相同的矩形边界,只有部分图像是透明的。

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

1 个答案:

答案 0 :(得分:10)

你能把图像放在UIImageView吗?如果是这样的话:

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

如果您想要修改UIImage本身,您可能需要添加类似- (UIImage)hexagonImage的类别方法,该方法将图像绘制到由您的六边形路径剪切的CGGraphicsContextCGContextClipPath,然后返回从图形上下文创建的UIImage

修改:这是代码示例

(注意:在构建我的答案时我有点失望,你可以看到下面提到的两种技术,以及用于生成UIBezierPath n 的一些代码 - gon,在ZEPolygon)的示例项目中

方法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];

方法2:UIImage上的类别返回蒙版版本

UIImage+PolygonMasking.h

#import <UIKit/UIKit.h>

@interface UIImage (ABCPolygonMasking)

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

@end

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