Маскировка пользовательской фигуры с помощью UIImageView

Я хочу программно обрезать фигуру над моим UIImageView. Я знаю о создании пути с QuartzCore, но я не понимаю контекст. Дайте мне пример, создав подкласс UIImageView.

Итак, как я могу сделать изображение пойти из этого:

Оригинальная обложка альбома

К этому:

Обрезанная обложка альбома

Мне также нужна маска, чтобы быть прозрачной

1 ответ

Самый простой подход заключается в

  • создать 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;
}

Я опубликовал еще один ответ, который иллюстрирует идею с закругленными углами тоже.

Если вы хотите реализовать добавление этой маски как часть UIImageView подкласс, я оставлю это вам. Но, надеюсь, это иллюстрирует основную идею.

Другие вопросы по тегам