Question

I am trying to draw a bar. I have set stroke color and fill color. Though I am setting the path with fill color, its not getting filled.This code draws a rectangle.

 blocks = yValue / yInterval; //Total number of blocks
    divider = (self.bounds.size.height * 0.75 - 100)/ blocks ;//height for each block

    float factor = value / yValue;
        //NSLog(@"%f",factor);
        int size = 40;
        [[UIColor redColor] setFill];
        [[UIColor redColor] setStroke];
        UIBezierPath *path = [[UIBezierPath alloc]init];

        CGPoint x1 = CGPointMake(0 + 100 + (index * size), self.bounds.size.height * 0.75);
        CGPoint x2 = CGPointMake(x1.x + size,self.bounds.size.height * 0.75 );
       // float height = (self.bounds.size.height * 0.75) - ((self.bounds.size.height * 0.75) * factor) + 5;
        float height = self.bounds.size.height * 0.75 - (divider * factor * blocks);
        CGPoint y1 = CGPointMake(x1.x, height);
        CGPoint y2 = CGPointMake(x2.x, height);

        [path moveToPoint:x1];
        [path addLineToPoint:x2];
        [path moveToPoint:x2];
        [path addLineToPoint:y2];
        [path moveToPoint:y2];
        [path addLineToPoint:y1];
        [path moveToPoint:y1];
        [path addLineToPoint:x1];

        [path closePath];
        [path fill];
        [path stroke];`
Was it helpful?

Solution

This is because you're not drawing a closed path properly. You're just drawing 4 separate lines.

Try this...

// all your setup code...

[path moveToPoint:x1];
[path addLineToPoint:x2];
[path addLineToPoint:y2];
[path addLineToPoint:y1];
[path addLineToPoint:x1];

[path closePath];
[path fill];
[path stroke];

This should work.

A bit of explanation

From the docs the closePath method...

Closes the current subpath by creating a line segment between the first and last points of the current subpath.

moveToPoint will start a new subPath within the current path.

This is used thusly...

Move to P1.     Path = 0.
Add line to P2. Path = P1-P2.
Add line to P3. Path = P1-P2-P3.
Close path.     Path = P1-P2-P3(-P1).

What you are doing is...

Move to P1.     Path = 0.
Add line to P2. Path = P1-P2.
Move to P2.     Path = P1-P2.
Add line to P3. Path = P1-P2 | P2-P3.
Move to P3.     Path = P1-P2 | P2-P3.
Add line to P1. Path = P1-P2 | P2-P3 | P3-P1.
Close path.     Path = P1-P2 | P2-P3 | P3-P1(-P3).

All you have closed is the last line subpath. Moving to a point will start a new subpath in the path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top