iPhone 简单的重画

在UIView中,重写drawRect: (CGRect) aRect方法,可以自己定义想要画的图案.且此方法一般情况下只会画一次.也就是说这个drawRect方法一般情况下只会被掉用一次.

 

当某些情况下想要手动重画这个View,只需要掉用[self setNeedsDisplay]方法即可.

drawRect掉用是在Controller->loadView, Controller->viewDidLoad 两方法之后掉用的.所以不用担心在控制器中,这些View的drawRect就开始画了.这样可以在控制器中设置一些值给View(如果这些View draw的时候需要用到某些变量值).

 

下面是一个drawRect 方法片段的一个示列,画一条线,线的两端各带一个小圆圈

 

- (void) drawRect: (CGRect) aRect
{
	NSLog(@"DRAW RECT...");
	
	// Get the current context
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextClearRect(context, aRect);
	
	// Set up the stroke and fill characteristics
	CGContextSetLineWidth(context, 3.0f);
	CGFloat gray[4] = {0.5f, 0.5f, 0.5f, 1.0f};
	CGContextSetStrokeColor(context, gray);
	CGFloat red[4] = {0.75f, 0.25f, 0.25f, 1.0f};
	CGContextSetFillColor(context, red);
	
	// Draw a line between the two location points
	CGContextMoveToPoint(context, self.loc1.x, self.loc1.y);
	CGContextAddLineToPoint(context, self.loc2.x, self.loc2.y);
	CGContextStrokePath(context);
	
	CGRect p1box = CGRectMake(self.loc1.x, self.loc1.y, 0.0f, 0.0f);
	CGRect p2box = CGRectMake(self.loc2.x, self.loc2.y, 0.0f, 0.0f);
	float offset = -8.0f;
	
	// circle point 1
	CGMutablePathRef path = CGPathCreateMutable();
	CGPathAddEllipseInRect(path, NULL, CGRectInset(p1box, offset, offset));
	CGContextAddPath(context, path);
	CGContextFillPath(context);
	CFRelease(path);
	
	// circle point 2
	path = CGPathCreateMutable();
	CGPathAddEllipseInRect(path, NULL, CGRectInset(p2box, offset, offset));
	CGContextAddPath(context, path);
	CGContextFillPath(context);	
	CFRelease(path);
}

你可能感兴趣的:(UP)