初学者iPhone问题:如何画矩形?我做错了什么?

7

我试图弄清楚我在这里做错了什么。尝试了几次,但我从未在屏幕上看到那个难以捉摸的矩形。现在,我只想在屏幕上绘制一个矩形。

除了CGContextSetRGBFillColor()之外,我在所有地方都收到“无效上下文”的错误提示。在此之后获取上下文似乎对我来说是错误的,但我不在家里看我昨晚使用的示例。

我还搞砸了其他东西吗?我真的很想今晚至少完成这么多...

- (id)initWithCoder:(NSCoder *)coder
{
  CGRect myRect;
  CGPoint myPoint;
  CGSize    mySize;
  CGContextRef context;

  if((self = [super initWithCoder:coder])) {
    NSLog(@"1");
    currentColor = [UIColor redColor];
    myPoint.x = (CGFloat)100;
    myPoint.y = (CGFloat)100;
    mySize.width = (CGFloat)50;
    mySize.height = (CGFloat)50;
    NSLog(@"2");
    // UIGraphicsPushContext (context);
    NSLog(@"3");
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, currentColor.CGColor);
    CGContextAddRect(context, myRect);
    CGContextFillRect(context, myRect);
  }

  return self;

}

感谢您,Sean。
2个回答

40

从View-based模板开始,创建一个名为 Drawer 的项目。在项目中添加一个UIView类,并将其命名为SquareView (.h和.m)。

双击 DrawerViewController.xib 以在Interface Builder中打开它。在身份信息检查器(command-4)中使用Class弹出菜单,将通用视图更改为SquareView。保存并返回Xcode

将以下代码放入 SquareView.m 文件的drawRect:方法中,以绘制一个大的、倾斜的、空心的黄色矩形和一个小的、绿色的、透明的正方形:

- (void)drawRect:(CGRect)rect;
{   
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line

    CGContextBeginPath(context);

    CGContextMoveToPoint(context, 50.0, 50.0); //start point
    CGContextAddLineToPoint(context, 250.0, 100.0);
    CGContextAddLineToPoint(context, 250.0, 350.0);
    CGContextAddLineToPoint(context, 50.0, 350.0); // end path

    CGContextClosePath(context); // close path

    CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it

    CGContextStrokePath(context); // do actual stroking

    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
    CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}

您不必调用此方法进行绘图。当程序启动并激活NIB文件时,您的视图控制器将至少一次地告诉视图绘制自身。


9

initWithCoder中不应该放置CG代码。该消息仅用于初始化目的。

将您的绘图代码放在以下位置:

- (void)drawRect:(CGRect)rect

如果您正在对UIView进行子类化...

12
同时,你不应该直接调用drawRect方法,而应该调用setNeedsDisplay方法,这样操作系统会在后续重新绘制视图。 - pgb
好的,所以我不应该使用initWithCoder()来绘制东西。但这真的回答了我的问题吗?将CG代码移动到另一个函数中是否会对矩形是否被绘制产生任何影响?至于使用/不使用drawRect,你现在已经让我感到困惑了。你是说我应该把矩形的所有参数都放在drawRect中吗?这似乎也不对——如果我想画多个矩形怎么办?如果有一个简单的示例应用程序,绘制一个矩形或圆形之类的东西,我想看一下。肖恩。 - Sean Gilley
1
是的,将您的代码移动到drawRect肯定会导致矩形绘制。我认为您应该在iPhone DEV上跟随一些基本教程,因为这是相当基础的东西。看看SDK附带的示例。 - Pablo Santa Cruz
1
drawRect方法是唯一一个你可以保证有一个可绘制上下文的地方,但前提是你不直接调用drawRect。 - Chris Lundie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接