2

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

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

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

没有把握。很想听听大家的想法。

4

1 回答 1

10

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

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

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

编辑:这里是代码示例

(注意:我在构建我的答案时有点不知所措,除了一些用于生成UIBezierPath n边形的代码外,您还可以在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];

方法二:category onUIImage返回一个被屏蔽的版本

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
于 2013-07-29T02:55:23.207 回答