用UIImageView掩盖自定义形状

问题描述:

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

所以,我怎么可以从这个图像去:

Original Album Cover

要这样:

Cropped Album Cover

我还需要面罩是透明的

最简单的方法是到

  • 为六角形创建一个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子类的一部分,我会将其留给您。但希望这可以说明基本的想法。