[英]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.