是否可以创建具有六角形角的UIImage或UIImageView?因为我想要一个UIImage并在UIImageView中显示它,但在内部和六边形。感谢
答案 0 :(得分:5)
过了一会儿,我发现了一个简单的实现。我创建了一个六角形视图:
HexagonView.h
#import <UIKit/UIKit.h>
@interface HexagonView : UIView
@end
HexagonView.m
#import "HexagonView.h"
#import <QuartzCore/QuartzCore.h>
@implementation HexagonView
- (void)drawRect:(CGRect)rect {
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.frame = self.bounds;
CGFloat width = self.frame.size.width;
CGFloat height = self.frame.size.height;
CGFloat hPadding = width * 1 / 8 / 2;
UIGraphicsBeginImageContext(self.frame.size);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(width/2, 0)];
[path addLineToPoint:CGPointMake(width - hPadding, height / 4)];
[path addLineToPoint:CGPointMake(width - hPadding, height * 3 / 4)];
[path addLineToPoint:CGPointMake(width / 2, height)];
[path addLineToPoint:CGPointMake(hPadding, height * 3 / 4)];
[path addLineToPoint:CGPointMake(hPadding, height / 4)];
[path closePath];
[path closePath];
[path fill];
[path stroke];
maskLayer.path = path.CGPath;
UIGraphicsEndImageContext();
self.layer.mask = maskLayer;
}
@end
然后我在HexagonView上添加了我的ImageView子视图:
[hexagonView addSubview:scaledImageView];
结果如下: