我正在尝试用手指在屏幕上绘制箭头。我的想法是通过触摸屏幕设置箭头的初始坐标,当我在屏幕上拖动时,箭头会延伸并跟随我的手指。箭头的高度和宽度将相同,重要的是箭头的大小。当我将它拖离起点时,箭头会变长。我试过用这样的东西东它:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UIGraphicsBeginImageContext(CGSizeMake(1536, 2048));
UITouch *touch = [touches anyObject];
CGPoint p1 = [touch locationInView:self.view];
CGSize size;
size.width = 50;
size.height = 400;
CGContextRef context = UIGraphicsGetCurrentContext();
[self drawArrowWithContext:context atPoint:p1 withSize:size lineWidth:4 arrowHeight:20 andColor:[UIColor whiteColor]];
// converts your context into a UIImage
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// Adds that image into an imageView and sticks it on the screen.
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
}
和
- (void) drawArrowWithContext:(CGContextRef)context atPoint:(CGPoint)startPoint withSize: (CGSize)size lineWidth:(float)width arrowHeight:(float)aheight andColor:(UIColor *)color
{
float width_wing = (size.width - width) / 2;
float main = size.height-aheight;
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextSetStrokeColorWithColor(context, [color CGColor]);
CGPoint rectangle_points[] = {
CGPointMake(startPoint.x + width_wing, startPoint.y + 0.0),
CGPointMake(startPoint.x + width_wing, startPoint.y + main),
CGPointMake(startPoint.x + 0.0, startPoint.y + main), // left point
CGPointMake(startPoint.x + size.width / 2, startPoint.y + size.height),
CGPointMake(startPoint.x + size.width, startPoint.y + main), // right point
CGPointMake(startPoint.x + size.width-width_wing, startPoint.y + main),
CGPointMake(startPoint.x + size.width-width_wing, startPoint.y + 0.0),
CGPointMake(startPoint.x + width_wing, startPoint.y + 0.0),
};
CGContextAddLines(context, rectangle_points, 8);
CGContextFillPath(context);
}
如果我从在普通 IBOutlet 中移动的触摸运行代码,箭头确实会出现在屏幕上,但这不是我的想法。我还没有设法让这段代码工作,但我认为即使它工作,它也会导致崩溃,因为我每次都在删除和重绘形状。这是正确的方法吗?我应该怎么办?