Search code examples
objective-cxcodedrawinguibezierpathcgrect

How to draw in rect with bezier path?


I have a some rect in my view and I want to draw a figure in that rect with UIBezierPath.

I thought that method

UIBezierPath myBezierPath = [UIBezierPath bezierPathWithRect:myRect]; 

will make an empty UIBezierPath called myBezierPath, with bounds that myRect gives to it, and then I can "draw" it that myBezierPath using moveToPoint and addLineToPoint. But, that code made a square (I'm stroke that path, so stroked square) with bounds that was in myRect. But I don't want him to be visible. I only want that if I try this:

NSLog(@"myBezierPath rect size %f,%f",myBezierPath.bounds.size.width,myBezierPath.bounds.size.height);

It returns me the width and height that myRect has. And therefore I can use it in my moveToPoint method and addLine method. For example like this:

[myBezierPath addLineToPoint: CGPointMake(suit.bounds.size.width/2, 0)];

Thanks.

My question is: «How can I draw in rect using bezier path?»

I made this with method, here myRect have origin that place CGRect with myBezierPath in center of the view.

myBezierPath = [UIBezierPath bezierPathWithRoundedRect:myRect cornerRadius:20.0];

Example 1 http://i.minus.com/iguFjeqZQrsb6.png

How can I made similar (place my another drawing to center with origin)? Now I have this:

Example 2 http://i.minus.com/ifVY9UAP7hVv3.png


Solution

  • Example (you will need a UIImageView in your interface):

    CGRect r = self.myImageView.bounds;
    UIGraphicsBeginImageContextWithOptions(r.size, NO, 0);
    UIBezierPath* p = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(r,10,10) cornerRadius:10];
    [p stroke];
    CGPoint c = CGPointMake(r.size.width/2.0, r.size.height/2.0);
    p = [UIBezierPath bezierPath];
    [p moveToPoint:CGPointMake(c.x-30, c.y)];
    [p addLineToPoint:CGPointMake(c.x, c.y-30)];
    [p addLineToPoint:CGPointMake(c.x+30, c.y)];
    [p addLineToPoint:CGPointMake(c.x, c.y+30)];
    [p closePath];
    [p fill];
    self.myImageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    enter image description here