繁体   English   中英

如何画一个矩形?

[英]How to draw a rectangle?

我想在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中做到这一点。 您需要扩展View并在“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);
}

为了清楚起见:

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

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

有:

 [[UIColor redColor] set];

您无法直接在viewDidLoad中渲染; 这是视图本身必须在他们的drawRect方法中运行它。

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

现代2018解决方案..

override func draw(_ rect: CGRect) {

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

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

而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM