2011-11-19 151 views
15

我想在viewContoller的视图中绘制填充的矩形。 我在viewDidLoad中写了下面的代码。但没有改变。 有什么不对?如何绘制矩形?

CGRect rectangle = CGRectMake(0, 100, 320, 100); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); 
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); 
CGContextFillRect(context, rectangle); 
+0

请注意,对于这个**非常老的问题**,我已经在现代答案2018 – Fattie

回答

41

你不能在viewController中做到这一点。 您需要扩大您的视图并将代码添加到“drawRect:”

这将改变您的视图的绘制逻辑。

-(void) drawRect:(CGRect)rect{  
[super drawRect:rect]; 
    CGRect rectangle = CGRectMake(0, 100, 320, 100); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); 
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); 
    CGContextFillRect(context, rectangle); 
} 
+2

+1中提供了正确答案 - 尽管我不会忽略drawRect的CGRect参数.... – Till

+0

对,我想一个更好的解决方案是首先验证需要重绘的区域是矩形的一部分,然后才能做到。 –

+0

你是什么意思扩展视图? – charly

2

你不能在viewDidLoad中直接渲染;这是它们自己的观点必须在drawRect方法中运行它。

“绘制”矩形的最简单方法是在您的视图中放置一个带有背景颜色&边框的UIView。 (您可以通过视图的CALayer的的方法,设置边界,即myView.layer.borderColor = [[UIColor redColor] CGColor];。)

1

只是为了清晰:

如果您需要绘制具有相同的填充和边框颜色的矩形,然后您可以更换:

CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); 
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); 

有:

[[UIColor redColor] set]; 
0

现代2018解决方案..

override func draw(_ rect: CGRect) { 

    let r = CGRect(x: 5, y: 5, width: 10, height: 10) 

    UIColor.yellow.set() 
    UIRectFill(r) 
} 

就是这样。