Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a rectangle?

I want to draw a filled rectangle in my viewContoller's view. I wrote the code below in viewDidLoad. But there is no change. What is wrong?

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);
like image 632
charly Avatar asked Nov 19 '11 15:11

charly


2 Answers

You can't do it in a viewController. You need to extend your View and add the code under "drawRect:"

this will change the drawing logic of your view.

-(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);
}
like image 188
Guy Ephraim Avatar answered Nov 16 '22 00:11

Guy Ephraim


modern 2018 solution..

override func draw(_ rect: CGRect) {

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

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

that's it.

like image 26
Fattie Avatar answered Nov 16 '22 00:11

Fattie