问题
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
回答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
回答2:
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));
来源:https://stackoverflow.com/questions/10527727/drawing-rectangle-on-button-click-in-viewcontroller-class-in-objective-c-ios5