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;

}

谢谢,

肖恩。

4

2 回答 2

40

从基于视图的模板开始,创建一个名为Drawer的项目。将 UIView 类添加到您的项目中。将其命名为SquareView(.h 和 .m)。

双击DrawerViewController.xib以在Interface Builder中打开它。使用Class弹出菜单在 Identity Inspector (command-4)中将通用视图更改为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 文件时,您的视图控制器将告诉视图至少绘制一次自己。

于 2009-07-18T09:58:12.387 回答
9

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

将您的绘图代码放入:

- (void)drawRect:(CGRect)rect

如果您正在继承 UIView...

于 2009-06-09T13:50:50.313 回答