PgmFreek
PgmFreek

Reputation: 6402

Draw and fill a rectangle in iPhone

I have 4 points say (x1,y1), (x2,y2), (x2,y3) and (x4,y4). I need a draw a rectangle with these points and fill a color inside that rect. Can any one help me with this?

Upvotes: 3

Views: 9203

Answers (3)

ingconti
ingconti

Reputation: 11666

If You need the same for swift 4.2:

  func drawOldStyle() {

        guard let context = UIGraphicsGetCurrentContext() else{
            return
        }


        //Next, define the rectangle:
        let myRect = CGRect(x: 30, y: 100, width: 100, height: 20)

        //Now, set the fill color, e.g red
        context.setFillColor(UIColor.red.cgColor)

        //Set the stroke color, e.g. green:
        context.setFillColor(UIColor.green.cgColor)

        //Finally, fill the rectangle:
        context.fill( myRect)

        // AND Stroke:
        context.stroke(myRect)

    }

Upvotes: 1

Max MacLeod
Max MacLeod

Reputation: 26682

First, get the current graphics context:

CGContextRef context = UIGraphicsGetCurrentContext();

Next, define the rectangle:

CGRect myRect = {x1, y1, x2 - x1, y2 - y1};

Now, set the fill color, e.g red

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

Set the stroke color, e.g. green:

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

Finally, fill the rectangle:

CGContextFillRect(context, myRect);

Upvotes: 24

jrturton
jrturton

Reputation: 119292

Create a UIBezierPath object. Move to your first point, then call addLineToPoint: for your subsequent three points. Then call closePath.

You can now fill or stroke this path, or obtain the CGPath if you want to use core graphics.

See here for the documentation.

Upvotes: 2

Related Questions