jayr parro
jayr parro

Reputation: 286

drawing hexagon using UIBezierPath

I'm drawing a hexagon using the UIBezierPath in which its points (or intersection) varies & controlled by slider. Pls. see the screenshot here: http://postimage.org/image/tq8z8t9qb/

The problem now, is that, when the last point is drawn or move it's already wrong (I've marked the screenshot in circle ). I think, it's drawn an extra line from the origin/center point of the bezier path. Hope you can check the code:

- (void)drawRect:(CGRect)rect
{
   // Drawing code
   CGContextRef ctx = UIGraphicsGetCurrentContext();
   CGContextClearRect(ctx, rect);    
   CGPoint center = CGPointMake(150.0, 150.0);

   // line
   UIBezierPath *polyPath = [UIBezierPath bezierPath];
   polyPath.lineWidth = 5;
   [polyPath moveToPoint:CGPointMake(center.x, center.y + 60.0)];

   for (int i = 1; i <= 6; ++i) {
      CGFloat x, y;

      NSNumber *oNumb = [[self aIndexValues] objectAtIndex:i-1];
      fXValue_ = [oNumb floatValue];
      x = fXValue_ * sinf(i * 2.0 * M_PI / 6.0);
      y = fXValue_ * cosf(i * 2.0 * M_PI / 6.0);

      [polyPath addLineToPoint:CGPointMake(center.x + x, center.y + y)];
    }

    [polyPath closePath];
    [[UIColor redColor] setStroke];
    [polyPath stroke];

    // circle point
    for(int i = 1; i <= 6; ++i) {
       CGFloat x, y;
       NSNumber *oNumb = [[self aIndexValues] objectAtIndex:i-1];
       fXValue_ = [oNumb floatValue];            
       x = fXValue_ * sinf(i * 2.0 * M_PI / 6.0);
       y = fXValue_ * cosf(i * 2.0 * M_PI / 6.0);

       UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(center.x + x - 6, center.y + y - 6, 15, 15)];  
       circle.lineWidth = 5;
       [[UIColor whiteColor] setFill];
       [circle fill];
    }
 }

Pls. let me know what's wrong. Thanks

Upvotes: 1

Views: 1605

Answers (1)

Cowirrie
Cowirrie

Reputation: 7226

Take a close look here:

[polyPath moveToPoint:CGPointMake(center.x, center.y + 60.0)];

This always draws to the maximum lower vertex of the hexagon, ignoring the slider setting for that vertex. It should probably use the approriate element of aIndexValues instead of 60.0.

A few other things that don't prevent this working, but make your code untidy:

  1. You don't need to call CGContextClearRect in drawRect. The context is already cleared for you.
  2. You're using a variable called fXValue_, which is not defined in this method. You don't need its value from elsewhere, so declare a variable within this method to store the vertex radius.
  3. See if you can find a clean way to count i from 0 to 5 instead of 1 to 6, so avoid having to subtract 1 whenever you retrieve numbers from aIndexValues.

Upvotes: 0

Related Questions