我正在尝试实现一个迷宫游戏,该游戏将通过开发的代码绘制自己的关卡drawRect
,我只需要知道如何检测将由代码绘制的图像内容的边界,
我正在使用UIButton
以下代码进行拖动:
- (void)viewDidLoad
{
[super viewDidLoad];
map = [[mapView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
[self.view addSubview:map];
self.view.backgroundColor = [UIColor blackColor];
meButton = [UIButton buttonWithType:UIButtonTypeCustom];
[meButton setTitle:@"Drag me!" forState:UIControlStateNormal];
meButton.backgroundColor = [UIColor yellowColor];
[meButton addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
meButton.frame = CGRectMake(100,100,50, 50);
[self.view addSubview:meButton];
}
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
UITouch *touch = [[event touchesForView:button] anyObject];
CGPoint previousLocation = [touch previousLocationInView:button];
CGPoint location = [touch locationInView:button];
CGFloat delta_x = location.x - previousLocation.x;
CGFloat delta_y = location.y - previousLocation.y;
// move button
button.center = CGPointMake(button.center.x + delta_x,
button.center.y + delta_y);
if(CGRectIntersectsRect(button.frame, map.frame)) {
NSLog(@"CGRectIntersectsRect");
}
}
此代码用于绘制地图(仍未正确实现)
- (void)drawRect:(CGRect)rect;
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line
CGContextBeginPath(context);
CGContextMoveToPoint(context, 50.0, 50.0); //start point
CGContextAddLineToPoint(context, 250.0, 100.0);
CGContextAddLineToPoint(context, 250.0, 350.0);
CGContextAddLineToPoint(context, 50.0, 350.0); // end path
CGContextClosePath(context); // close path
CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it
CGContextStrokePath(context); // do actual stroking
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}