How to draw a rectangle?
Asked Answered
C

4

15

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);
Cotangent answered 19/11, 2011 at 15:42 Comment(1)
please note, for this extremely old question, I've put in the modern answer, 2018Chak
V
45

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);
}
Vasculum answered 19/11, 2011 at 15:50 Comment(5)
+1 for correct answer - though I would not ignore the CGRect parameter of drawRect....Whimper
Right, I guess a better solution is to first verify that the area that needs to be re-drawn is part of the rectangle, and only then do it.Vasculum
What do you mean extend view?Cotangent
Create a new class for your view extending UIViewVasculum
No need to call super here; as it says in the Apple UIView class reference: "If you subclass UIView directly, your implementation of this method does not need to call super."Feinstein
C
6

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.

Chak answered 10/3, 2018 at 16:38 Comment(0)
P
4

Just for clarity:

If You need to draw a rectangle which has the same fill and border color, then You can replace:

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

with:

 [[UIColor redColor] set];
Poilu answered 4/3, 2014 at 12:15 Comment(0)
D
3

You can't render directly in viewDidLoad; it's the views themselves that would have to run this in their drawRect method.

The easiest way to "draw" a rectangle is to place a UIView with a background color & border in your view. (You can set the border via the view's CALayer's methods. i.e. myView.layer.borderColor = [[UIColor redColor] CGColor];)

Dimenhydrinate answered 19/11, 2011 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.