【问题标题】:Crop UIImage in shape of a hexagon?将 UIImage 裁剪为六边形?
【发布时间】:2013-07-27 11:40:41
【问题描述】:

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

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

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

不确定。很想听听大家的想法。

【问题讨论】:

  • 只是为了澄清。这里的“作物”是什么意思?生成的图像仍将像以前一样具有边界,那么您希望六边形之外的图像数据发生什么?您希望它是透明的并将生成的图像保存到磁盘吗?你想直接绘制没有被六边形遮住的部分的图像吗?

标签: ios uiimage crop


【解决方案1】:

你能把图片放在UIImageView 吗?如果是这样:

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

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

编辑:这里是代码示例

(注意:我在构建答案时有点忘乎所以,除了一些用于生成UIBezierPathn-gon 的代码之外,您还可以看到下面提到的两种技术,在ZEPolygon的示例项目中)

方法一:用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

【讨论】:

  • Zev - 非常感谢您对如何做的高级概述。但是 - 我对 CA 和修改图像几乎没有经验。如果有机会,您介意发布代码示例吗?这将不胜感激!谢谢。
猜你喜欢
  • 2012-02-05
  • 1970-01-01
  • 2017-06-13
  • 2017-11-10
  • 2011-09-25
  • 2017-10-28
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多