【问题标题】:create a UIImage or UIImageView with hexagonal corners创建一个带有六角的 UIImage 或 UIImageView
【发布时间】:2014-11-21 13:50:36
【问题描述】:

是否可以创建一个六角形的 UIImage 或 UIImageView?因为我想要一个 UIImage 并在 UIImageView 内部显示它,但在内部和六边形。谢谢

【问题讨论】:

  • 你可以使用这个库github.com/mattgemmell/MGImageUtilities
  • 是的,一切皆有可能。
  • @holex,当然,但是如何?
  • 您可以创建UIImageView 的子集,并且可以覆盖–drawRect: 方法,例如使用常规六边形遮盖实际内容,您可以使用 CoreGraphics.framework 创建该六边形遮罩。小菜一碟。

标签: ios objective-c uiimage


【解决方案1】:

过了一会儿,我找到了一个简单的实现。我创建了一个六边形视图:

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

结果是这样的:

【讨论】:

  • 你知道如何把它的所有 6 个角都弄圆
  • 检查这个答案stackoverflow.com/questions/20442203/…(好吧,它适用于三角形,但您可以将相同的方式应用于六边形)
  • 我可以添加它的边框吗?
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多