如何绘制矩形?
问题描述:
我想在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);
答
你不能在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);
}
答
你不能在viewDidLoad中直接渲染;这是它们自己的观点必须在drawRect方法中运行它。
“绘制”矩形的最简单方法是在您的视图中放置一个带有背景颜色&边框的UIView。 (您可以通过视图的CALayer的的方法,设置边界,即myView.layer.borderColor = [[UIColor redColor] CGColor];
。)
答
只是为了清晰:
如果您需要绘制具有相同的填充和边框颜色的矩形,然后您可以更换:
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
有:
[[UIColor redColor] set];
答
现代2018解决方案..
override func draw(_ rect: CGRect) {
let r = CGRect(x: 5, y: 5, width: 10, height: 10)
UIColor.yellow.set()
UIRectFill(r)
}
就是这样。
请注意,对于这个**非常老的问题**,我已经在现代答案2018 – Fattie