[英]Crop UIImage in shape of a hexagon?
所以我已经看到了如何将UIImages裁剪成某些形状的解决方案,但是六边形呢?
一个想法:子类UIImage,改变drawRect方法只绘制某些部分?
编辑:更具体一点,我希望保持图像边界相同,但使六边形外的图像数据透明,所以看起来图像是六边形的形状,实际上它有相同的矩形边界,只有部分图像是透明的。
不确定。 很想听听你们的想法。
你能把图像放在UIImageView
吗? 如果是这样的话:
创建一个新的CAShapeLayer
(记得导入QuartzCore!)。 创建六边形的CGPathRef
或UIBezierPath
,并将其设置为形状图层的path
属性。 将形状图层设置为图像视图图层的mask
。
如果你想修改UIImage
本身,你可能想要添加一个类别方法,如- (UIImage)hexagonImage
,它将图像绘制成一个CGGraphicsContext
,使用CGContextClipPath
剪切你的六边形路径,然后返回一个UIImage
图形创建的UIImage
上下文。
编辑 :这是代码示例
(注意:在构建我的答案时,我有点遗憾,除了在ZEPolygon的示例项目中生成UIBezierPath
n -gon的一些代码之外,您还可以看到下面提到的两种技术)
方法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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.