0

simply I am beginner in developing on ipad and I need to draw rectangle at point x,y with width and height when i clicked or touched button .

I searched on google but i didn't find anything working in button handler

Prasad G
  • 6,702
  • 7
  • 42
  • 65
kartal
  • 17,436
  • 34
  • 100
  • 145

2 Answers2

1

Create rectangleButton in viewDidLoad method and write -(void)rectangleButtonSelected method in your ViewController.m. And also create class RectangleView of UIView.

-(void)rectangleButtonSelected{

    RectangleView *temp = [[RectangleView alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];

    temp.center = CGPointMake(arc4random()%100, arc4random()%200);
    NSLog(@"The Main center Point : %f  %f",temp.center.x,temp.center.y);

    [self.view addSubview:temp];

}

Implement - (void)drawRect:(CGRect)rect method in RectanglerView.m

- (void)drawRect:(CGRect)rect
{

    // Drawing code

    context =UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
    // And draw with a blue fill color
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0);


    CGContextAddRect(context, self.bounds);
    CGContextStrokePath(context);


    // Close the path
    CGContextClosePath(context);
    // Fill & stroke the path
    CGContextDrawPath(context, kCGPathFillStroke);
}

I hope it will be helpful to you

Prasad G
  • 6,702
  • 7
  • 42
  • 65
0

You actually need to do this with state. There's only one place you're allowed to do drawing, and that's in drawRect:. So, when the user clicks the button, you need to set some instance variable, like _isShowingRectangle or something, then call setNeedsDisplay on your custom UIView where you're doing your drawing.

Then, in your custom view's drawRect:, you can check if that state variable is set, and draw (or not draw) the rectangle. The code for drawing depends on which graphics layer you're using, but it's probably going to be something like

CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(ctxt,[[UIColor blackColor] CGColor]);
CGContextSetLineWidth(ctxt,3.0);
CGContextStrokeRect(ctxt,CGRectMake(10,20,100,50));
Morgan Harris
  • 2,589
  • 14
  • 17
  • that mean i need to create new class as UIview and set custum class to the new one ok how can i connect between this 2 class and setNeedsDisplay can you give me example i know the code of drawing but my problem is the code or calling the drawing function – kartal May 10 '12 at 05:17