通过按下按钮在Quartz 2D中绘图

时间:2014-08-14 04:04:02

标签: objective-c xcode

我在Objective-C中有点小说,我刚开始使用Quartz 2D。我的问题很简单:我想通过按下按钮在Quartz 2D中绘图。我不知道怎么做,因为我的项目中有两个不同的类。我使用了那个教程:http://www.techotopia.com/index.php/An_iOS_7_Graphics_Tutorial_using_Core_Graphics_and_Core_Image

这是我的代码:

ViewController.h
@interface ViewController : UIViewController
- (IBAction)Start;
ViewController.m
- (IBAction)Start {
}
Draw2D.h
#import <UIKit/UIKit.h>
@interface Draw2D : UIView
@end
Draw2D.m
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
}
return self;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, 30, 30);
CGContextAddLineToPoint(context, 300, 400);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);
}



- (void)drawRect:(CGRect)rect {

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);
CGContextSetStrokeColorWithColor(context,
                                 [UIColor blueColor].CGColor);
CGRect rectangle = CGRectMake(60,170,200,80);
CGContextAddRect(context, rectangle);
CGContextStrokePath(context);
}

1 个答案:

答案 0 :(得分:0)

如果要在按下按钮时显示Draw2D视图,可以将draw2DView添加为ViewController的子视图:

/// ViewController
- (IBAction)Start:(UIButton *)sender
{
   [self.view addSubview:draw2DView]; 
}

你应该在Draw2D initWithFrame方法中删除这些行

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, 30, 30);
CGContextAddLineToPoint(context, 300, 400);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);

它们低于return self;因此不会被触发。