Как нарисовать один закругленный угол моего UIView. - PullRequest
17 голосов
/ 28 августа 2010

Привет!Я хочу нарисовать закругленный угол моего UIView. Только один , другие не могут быть изменены.

Ответы [ 4 ]

65 голосов
/ 29 апреля 2011

Начиная с iOS 3.2, вы можете использовать функциональность UIBezierPath s для создания прямоугольного прямоугольника с закругленными углами (только закругленные углы) Затем вы можете использовать это как путь к CAShapeLayer и использовать это как маску для слоя вашего вида:

// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                                               byRoundingCorners:UIRectCornerTopLeft
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = imageView.bounds;
maskLayer.path = maskPath.CGPath;

// Set the newly created shape layer as the mask for the image view's layer
imageView.layer.mask = maskLayer;

И это все - не нужно возиться с определением фигур вручную в Core Graphics, не создавать маскирующие изображения в Photoshop. Слой даже не нуждается в аннулировании. Применение закругленного угла или переход к новому углу так же просто, как определение нового UIBezierPath и использование его CGPath в качестве пути слоя маски. Параметр corners метода bezierPathWithRoundedRect:byRoundingCorners:cornerRadii: является битовой маской, поэтому несколько углов могут быть округлены путем ИЛИ их вместе.

ПРИМЕЧАНИЕ - Маски слоя не будут отображаться при использовании в сочетании с методом CALayer renderInContext. Если вам нужно использовать это, попробуйте скруглить углы следующим образом: Всего два закругленных угла? .

2 голосов
/ 10 ноября 2011

Я сделал метод ответа StuDev:

+ (CAShapeLayer *) roundedCornerOnImage: (UIImageView *)imageView onCorner: (UIRectCorner)rectCorner
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                                                   byRoundingCorners:rectCorner
                                                         cornerRadii:CGSizeMake(10.0, 10.0)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = imageView.bounds;
    maskLayer.path = maskPath.CGPath;

    return maskLayer;
}

Пример использования изображения в UITableViewCell:

if (indexPath.row == 0)
    cell.imageView.layer.mask = [Helper roundedCornerOnImage:cell.imageView onCorner:UIRectCornerTopLeft];
else if (indexPath.row == self.arrayPeople.count - 1)
    cell.imageView.layer.mask = [Helper roundedCornerOnImage:cell.imageView onCorner:UIRectCornerBottomLeft];

Спасибо StuDev за отличное решение!

0 голосов
/ 19 ноября 2015

Я сделал функцию для создания собственного радиуса угла после небольшого исследования:

+(void)setConerRadiusForTopLeft:(BOOL)isForTopLeft ForTopRight:(BOOL)isForTopRight ForBottomLeft:(BOOL)isForBottomLeft  ForBottomRight:(BOOL)isForBottomRight withCornerRadius:(float)cornerRadius forView:(UIView *)view
{

    UIRectCorner corners = (isForTopLeft ? UIRectCornerTopLeft : 0) |
                          (isForTopRight ? UIRectCornerTopRight : 0) |
                          (isForBottomLeft ? UIRectCornerBottomLeft : 0) |
                          (isForBottomRight ? UIRectCornerBottomRight : 0);

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                               byRoundingCorners:corners
                                                     cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}
0 голосов
/ 12 марта 2014
+ (CAShapeLayer *) roundedCornerOnImage: (UIImageView *)imageView onCorner: (UIRectCorner)rectCorner
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                                                   byRoundingCorners:rectCorner
                                                         cornerRadii:CGSizeMake(10.0, 10.0)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = imageView.bounds;
    maskLayer.path = maskPath.CGPath;
    imageView.layer.mask=maskLayer
    return maskLayer;
}


if (indexPath.row == 0)
    [Helper roundedCornerOnImage:cell.imageView onCorner:UIRectCornerTopLeft];
else if (indexPath.row == self.arrayPeople.count - 1)
  [Helper roundedCornerOnImage:cell.imageView onCorner:UIRectCornerBottomLeft];

Обновленный ответ выше, вам не нужно возвращаться и управлять этим.Это можно сделать с помощью этой функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...