试图找出我在这里做错了什么.尝试了几件事,但我从未在屏幕上看到那个难以捉摸的矩形.现在,这就是我想做的 - 只需在屏幕上绘制一个矩形.
我在除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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢,
肖恩.
wil*_*lc2 40
从基于视图的模板开始,创建名为Drawer的项目.将UIView类添加到项目中.将其命名为SquareView(.h和.m).
双击DrawerViewController.xib以在Interface Builder中打开它.使用" 类"弹出菜单将Identity中的通用视图更改为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
}
Run Code Online (Sandbox Code Playgroud)
您不必为绘图调用此方法.当程序启动并激活NIB文件时,视图控制器将告诉视图至少绘制一次.
你不应该把CG代码放在initWithCoder中.该消息仅应用于INITIALIZATION目的.
将您的绘图代码放入:
- (void)drawRect:(CGRect)rect
Run Code Online (Sandbox Code Playgroud)
如果你是UIView的子类......
| 归档时间: |
|
| 查看次数: |
32828 次 |
| 最近记录: |