使用UIImageView屏蔽自定义形状

时间:2014-09-28 18:24:41

标签: objective-c quartz-core

我想在我的UIImageView上以编程方式裁剪一个形状。我知道用QuartzCore创建一个路径,但我不了解上下文。通过继承UIImageView给我一个例子。

那么我怎么能从中得到一个图像:

Original Album Cover

对此:

Cropped Album Cover

我还需要遮罩是透明的

1 个答案:

答案 0 :(得分:4)

最简单的方法是

  • 为六边形创建UIBezierPath;
  • 从该路径创建CAShapeLayer;和
  • CAShapeLayer作为掩码添加到图片视图layer

因此,它可能看起来像:

CAShapeLayer *mask = [CAShapeLayer layer];
mask.path          = [[self polygonPathWithRect:self.imageView.bounds lineWidth:0.0 sides:6] CGPath];
mask.strokeColor   = [UIColor clearColor].CGColor;
mask.fillColor     = [UIColor whiteColor].CGColor;
self.imageView.layer.mask = mask;

,其中

/** Create UIBezierPath for regular polygon inside a CGRect
 *
 * @param square        The CGRect of the square in which the path should be created.
 * @param lineWidth     The width of the stroke around the polygon. The polygon will be inset such that the stroke stays within the above square.
 * @param sides         How many sides to the polygon (e.g. 6=hexagon; 8=octagon, etc.).
 *
 * @return              UIBezierPath of the resulting polygon path.
 */

- (UIBezierPath *)polygonPathWithRect:(CGRect)square
                            lineWidth:(CGFloat)lineWidth
                                sides:(NSInteger)sides
{
    UIBezierPath *path  = [UIBezierPath bezierPath];

    CGFloat theta       = 2.0 * M_PI / sides;                           // how much to turn at every corner
    CGFloat squareWidth = MIN(square.size.width, square.size.height);   // width of the square

    // calculate the length of the sides of the polygon

    CGFloat length      = squareWidth - lineWidth;
    if (sides % 4 != 0) {                                               // if not dealing with polygon which will be square with all sides ...
        length = length * cosf(theta / 2.0);                            // ... offset it inside a circle inside the square
    }
    CGFloat sideLength = length * tanf(theta / 2.0);

    // start drawing at `point` in lower right corner

    CGPoint point = CGPointMake(squareWidth / 2.0 + sideLength / 2.0, squareWidth - (squareWidth - length) / 2.0);
    CGFloat angle = M_PI;
    [path moveToPoint:point];

    // draw the sides and rounded corners of the polygon

    for (NSInteger side = 0; side < sides; side++) {
        point = CGPointMake(point.x + sideLength * cosf(angle), point.y + sideLength * sinf(angle));
        [path addLineToPoint:point];
        angle += theta;
    }

    [path closePath];

    return path;
}

我发布了另一个用rounded corners来说明这个想法的答案。

如果你想将这个掩码添加为UIImageView子类的一部分,我将把它留给你。但希望这说明了基本的想法。