我正試圖在屏幕上使用我的手指繪製箭頭。這個想法是,通過觸摸屏幕我設置了我的箭頭的初始座標,當我在屏幕上拖動時,箭頭會延伸並跟隨我的手指。箭頭的高度和寬度將相同,即箭頭的大小。當我將它拖離起點時,箭頭會更長。我試圖董它是這樣的:使用TouchesMoved繪製形狀
- (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中移動的代碼,但這不是理念。我還沒有設法讓這段代碼工作,但我認爲即使它工作,它也會導致崩潰,因爲我每次都刪除並重繪形狀。這是正確的方法嗎?我該怎麼辦?
我不認爲添加大量的UIImageViews是一個好方法,特別是因爲您已經使用CoreGraphics。 – 2013-01-22 20:12:36
我知道,但我怎麼做,否則? – Alessandro
你並不總是開始一個新的圖像上下文,但你使用默認的,然後你畫箭頭。 – 2013-01-22 20:14:32