2014-09-28 72 views
2

我想以編程方式在我的UIImageView上裁剪形狀。我知道用QuartzCore創建路徑,但我不瞭解上下文。通過繼承UIImageView給我一個例子。用UIImageView掩蓋自定義形狀

所以,我怎麼可以從這個圖像去:

Original Album Cover

要這樣:

Cropped Album Cover

我還需要面罩是透明的

回答

3

最簡單的方法是到

  • 爲六角形創建一個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子類的一部分,我會將其留給您。但希望這可以說明基本的想法。