如何在控制器内部使用IBAction在自定义视图中绘制圆圈?

时间:2012-03-28 17:05:05

标签: objective-c draw ibaction

我删除了一个通用视图并将其连接到我的circleView.m。然后我拖出一个圆形的矩形按钮放在那个视图的顶部,并连接了一个IBAction。截至目前,当视图加载时,圆圈会自动绘制到屏幕上。我想做的是只有在使用drawRect或其他绘图方法按下按钮时才在屏幕上绘制圆圈。这是我的代码:

drawCircleViewController.h

#import <UIKit/UIKit.h>

@interface drawCircleViewController : UIViewController

@end

drawCircleViewController.m

#import "drawCircleViewController.h"
#import "circleView.h"
@interface drawCircleViewController()
@property (nonatomic, weak) IBOutlet circleView *circleV;
@end
@implementation drawCircleViewController
@synthesize circleV = _circleV;


- (IBAction)buttonPressedToDrawCircle:(id)sender {
    // This is action I want to use to draw the circle in my circleView.m 
}

@end

circleView.h

#import <UIKit/UIKit.h>

@interface circleView : UIView

@end

circleView.m

#import "circleView.h"

@implementation circleView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


- (void)drawCircleAtPoint:(CGPoint)p
               withRadius:(CGFloat)radius 
                inContext:(CGContextRef)context
{
    UIGraphicsPushContext(context);
    CGContextBeginPath(context);
    CGContextAddArc(context, p.x, p.y, radius, 0, 2*M_PI, YES);
    CGContextStrokePath(context);
    UIGraphicsPopContext();
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGPoint midpoint;
    midpoint.x = self.bounds.origin.x + self.bounds.size.width / 2;
    midpoint.y = self.bounds.origin.y + self.bounds.size.height / 2;

#define DEFAULT_SCALE 0.90

    CGFloat size = self.bounds.size.width / 2;
    if (self.bounds.size.height < self.bounds.size.width) size = self.bounds.size.height / 2;
    size *= DEFAULT_SCALE;

    CGContextSetLineWidth(context, 5.0);
    [[UIColor blueColor] setStroke];


    [self drawCircleAtPoint:midpoint withRadius:size inContext:context];
}

@end

1 个答案:

答案 0 :(得分:2)

根据你所拥有的,最简单的方法可能是隐藏圆形视图并在按下按钮时显示它。

否则,您可以在视图中保留BOOL以表示是否已点击按钮并在drawRect期间检查:(并使用setNeedsDisplay触发更改)。

相关问题