IOS - 绘制圆角方形

Dan*_*cer 4 objective-c cgcontext ios

我正在尝试创建一个带圆角的200px正方形,用作IOS吐司风格指示.

到目前为止,我有以下内容 -

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.1].CGColor);
    CGContextMoveToPoint(context, 10, 0);
    CGContextAddLineToPoint(context, 95, 0);
    CGContextAddArcToPoint(context, 100, 0, 100, 5, 10);
    CGContextAddLineToPoint(context, 100, 95);
    CGContextAddArcToPoint(context, 100, 100, 95, 100, 10);
    CGContextAddLineToPoint(context, 5, 100);
    CGContextAddArcToPoint(context, 0, 100, 0, 95, 10);
    CGContextAddLineToPoint(context, 0, 5);
    CGContextAddArcToPoint(context, 0, 0, 5, 0, 10);
    CGContextFillPath(context);
}
Run Code Online (Sandbox Code Playgroud)

我通过一个教程得到了这一点 - 它绘制了一个完美的100px圆角方形 - 但我需要一个150px的方形!我已经改变了所有可以设想的设置 - 有一些古怪的结果 - 但是无法弄清楚如何定义宽度高度!?任何人都可以建议吗?

Sim*_*lin 14

如果您导入QuartzCore框架:

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)

并将其添加到您的项目中,您可以使用以下内容:

UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
temp.layer.cornerRadius = 5;
Run Code Online (Sandbox Code Playgroud)

  • @downVoter关心解释?3人被投票,其他人说这是一个很好的解决方案.当人们在这样的情况下投票时,它会让我感到懊恼.很明显,我的一些代码存在问题,我很想知道,以便我可以像用户一样学习它.请分享 (2认同)
  • @Dancer Nah,在这种情况下使用cornerRadius要容易得多.通常,如果需要特殊形状,渐变等,则只使用drawRect. (2认同)

Tem*_*lar 10

如果您必须绘制drawRect并且将来会绘制其他东西,那么只需使用bezierpath,否则请参阅Simon对视图上简单圆角的回答

- (void)drawRect:(CGRect)rect {
       [super drawRect:rect];
       [[UIColor blueColor] setFill];
       UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect /*CGRectMake(0, 0, 150, 150)*/ cornerRadius:10.0];
       [path fill];
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*ust 5

  1. 将数字转换为变量/常量.

  2. 更改变量/常量值.

  3. 利润!

这是你的代码,修改后显示我的意思(未经测试):

- (void)drawRect:(CGRect)rect {
    static CGFloat length = 100;
    static CGFloat rounding = 5;

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.1].CGColor);
    CGContextMoveToPoint(context, rounding * 2, 0);
    CGContextAddLineToPoint(context, length - rounding, 0);
    CGContextAddArcToPoint(context, length, 0, length, rounding, rounding * 2);
    CGContextAddLineToPoint(context, length, length - rounding);
    CGContextAddArcToPoint(context, length, length, length - rounding, length, rounding * 2);
    CGContextAddLineToPoint(context, rounding, length);
    CGContextAddArcToPoint(context, 0, length, 0, length - rounding, rounding * 2);
    CGContextAddLineToPoint(context, 0, rounding);
    CGContextAddArcToPoint(context, 0, 0, rounding, 0, rounding * 2);
    CGContextFillPath(context);
}
Run Code Online (Sandbox Code Playgroud)

我也想知道你的代码中有10个.据我所知,他们应该是5s而不是.无论如何,更容易的解决方案是使用UIBezierPath其他人已经演示过的(层解决方案确实有效,但是如果您想要在圆角矩形下面绘制一些东西以及它上面的东西,它显然是行不通的).