Подтвердить что ты не робот

Только два закругленных угла?

В моем приложении iPad я хочу, чтобы второе представление отображалось в главном окне, когда пользователь нажимает кнопку. Новый вид будет меньше первого и затемнет фон при его отображении. Я хочу, чтобы верхние два угла нового вида выглядели округлыми, но с помощью cornerRadius все они округлены. Как я могу сделать только два угла округленными?

4b9b3361

Ответ 1

Вы должны сделать это в drawRect:. Я на самом деле изменил классический addRoundedRectToPath: так, что он принимает растровое изображение и округляет углы, которые вы запрашиваете:

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float radius, UIImageRoundedCorner cornerMask)
{
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius);
    CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius);
    if (cornerMask & UIImageRoundedCornerTopLeft) {
        CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius, 
                        radius, M_PI, M_PI / 2, 1);
    }
    else {
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y + rect.size.height);
    }

    CGContextAddLineToPoint(context, rect.origin.x + rect.size.width - radius, 
                          rect.origin.y + rect.size.height);

    if (cornerMask & UIImageRoundedCornerTopRight) {
        CGContextAddArc(context, rect.origin.x + rect.size.width - radius, 
                        rect.origin.y + rect.size.height - radius, radius, M_PI / 2, 0.0f, 1);
    }
    else {
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height - radius);
    }

    CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + radius);

    if (cornerMask & UIImageRoundedCornerBottomRight) {
        CGContextAddArc(context, rect.origin.x + rect.size.width - radius, rect.origin.y + radius, 
                        radius, 0.0f, -M_PI / 2, 1);
    }
    else {
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width - radius, rect.origin.y);
    }

    CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y);

    if (cornerMask & UIImageRoundedCornerBottomLeft) {
        CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius, 
                        -M_PI / 2, M_PI, 1);
    }
    else {
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + radius);
    }

    CGContextClosePath(context);
}

Это принимает битовую маску (я назвал ее UIImageRoundedCorner, потому что я делал это для изображений, но вы можете это назвать), а затем создает путь, основанный на углах, которые вы хотите округлить. Затем вы применяете этот путь к представлению в drawRect:

CGContextBeginPath(context);
addRoundedRectToPath(context, rect, radius, yourMask);
CGContextClosePath(context);
CGContextClip(context);

Как я уже сказал, я делал это для UIImages, поэтому мой код не совсем настроен для использования в drawRect:, но его довольно легко адаптировать. Вы в основном просто строите путь, а затем обрезаете контекст.

Изменить: Чтобы объяснить часть битмаски, это просто перечисление:

typedef enum {
    UIImageRoundedCornerTopLeft = 1,
    UIImageRoundedCornerTopRight = 1 << 1,
    UIImageRoundedCornerBottomRight = 1 << 2,
    UIImageRoundedCornerBottomLeft = 1 << 3
} UIImageRoundedCorner;

Таким образом, вы можете объединять элементы ИЛИ, чтобы сформировать битовую маску, которая идентифицирует углы, поскольку каждый член перечисления представляет другую силу в битовой маске.

Много позже Изменить: Я нашел более простой способ сделать это, используя UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:. Просто используйте объект пути bezier CGPath в вашем контексте.

Ответ 2

    // Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                          byRoundingCorners:UIRectCornerTopLeft| UIRectCornerTopRight
                          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 layer
imageView.layer.mask = maskLayer;

Это другое, чтобы использовать верхний округленный угол. Два раунда в UIView

Ответ 3

Замечательная работа Томека Куймы. Вот ваш новый класс TKRoundedView.
Ваше требование может выполняться только этим параметром.

TKRoundedView *view = [[TKRoundedView alloc] initWithFrame:frame];
view.roundedCorners = TKRoundedCornerTopLeft | TKRoundedCornerTopRight;

Но он также предоставляет следующие дополнительные функции.

TKRoundedView *view = [[TKRoundedView alloc] initWithFrame:frame];
view.roundedCorners = TKRoundedCornerTopLeft
view.borderColor = [UIColor greenColor];
view.fillColor = [UIColor whiteColor];
view.drawnBordersSides = TKDrawnBorderSidesLeft | TKDrawnBorderSidesTop;
view.borderWidth = 5.0f;
view.cornerRadius = 15.0f;

Пожалуйста, ознакомьтесь со следующей ссылкой для примера проекта
https://github.com/mapedd/TKRoundedView