【发布时间】:2012-09-17 23:10:03
【问题描述】:
我正在尝试遵循有关如何在屏幕上绘制一些形状的指南,但在应用程序启动时它工作正常,但我无法使用 setNeedsDisplay“重新绘制”这些形状我已经尝试了很多像在主线程上执行一样漂浮的东西,但它不起作用。
我的应用是由这个组成的:
我的 UIView 有它自己的类,DrawView。这是我的代码:
DrawView.h
#import <UIKit/UIKit.h>
NSInteger drawType;
@interface DrawView : UIView
-(void)drawRect:(CGRect)rect;
-(void)drawNow:(NSInteger)type;
@end
DrawView.m
#import "DrawView.h"
@implementation DrawView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *color = [UIColor orangeColor];
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetFillColorWithColor(context, color.CGColor);
NSLog(@"Type: %i",drawType);
switch (drawType) {
case 0:
CGContextMoveToPoint(context, 10, 100);
CGContextAddLineToPoint(context, 300, 300);
CGContextSetLineWidth(context, 2.0);
CGContextStrokePath(context);
break;
case 1:
CGContextAddEllipseInRect(context,CGRectMake(10, 100, 300,440));
CGContextDrawPath(context, kCGPathFillStroke);
break;
case 2:
CGContextAddRect(context, CGRectMake(10, 100,300,300));
CGContextDrawPath(context, kCGPathFillStroke);
break;
default:
break;
}
}
-(void)drawNow:(NSInteger)type {
drawType = type;
NSLog(@"Draw Now! %i",drawType);
//[self setNeedsDisplay]; // Not working...
//[self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; // Not Working
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import "DrawView.h"
DrawView *mydraw;
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISegmentedControl *drawTypeSW;
- (IBAction)drawNow:(id)sender;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize drawTypeSW;
- (void)viewDidLoad
{
[super viewDidLoad];
mydraw = [[DrawView alloc] init];
}
- (void)viewDidUnload
{
[self setDrawTypeSW:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)drawNow:(id)sender {
[mydraw drawNow:drawTypeSW.selectedSegmentIndex];
}
@end
当我打开应用程序时,会画一条线,但是当我尝试使用按钮 Draw Now 绘制其他内容时,它不起作用,没有任何反应,并且不会调用 - (void)drawRect:(CGRect)rect。为什么?我错过了什么?
谢谢;)
【问题讨论】:
标签: ios quartz-graphics quartz-2d cgrect