我想在UIImageView,
上繪製一個「消失的筆畫」,它會在觸摸事件之後進行並在固定時間延遲後自行擦除。這是我在ViewController中的。使用CGContextRef繪製自我擦除路徑
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
CGPoint lp = lastPoint;
UIColor *color = [UIColor blackColor];
[self drawLine:5 from:lastPoint to:currentPoint color:color blend:kCGBlendModeNormal];
double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self drawLine:brush from:lp to:currentPoint color:[UIColor clearColor] blend:kCGBlendModeClear];
});
lastPoint = currentPoint;
}
- (void)drawLine:(CGFloat)width from:(CGPoint)from to:(CGPoint)to color:(UIColor*)color blend:(CGBlendMode)mode {
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextMoveToPoint(context, from.x, from.y);
CGContextAddLineToPoint(context, to.x, to.y);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, width);
CGContextSetStrokeColorWithColor(context, [color CGColor]);
CGContextSetBlendMode(context, mode);
CGContextStrokePath(context);
self.tempDrawImage.image = UIGraphicsGetImageFromCurrentImageContext();
[self.tempDrawImage setAlpha:1];
UIGraphicsEndImageContext();
}
繪圖階段很好地工作,但後續擦除階段有幾個問題。
- 正確清除「填充」行時,路徑周圍會留下細小的筆劃。
- 「擦除階段」是波濤洶涌,遠不及繪圖階段那樣平滑。我最好的猜測是,這是由於
UIGraphicsBeginImageContext
運行在dispatch_after
的成本。
有沒有更好的方法來繪製自擦除線?
獎勵:我真的很喜歡「縮小和消失」的道路。換句話說,在延遲之後,我不希望清除描邊路徑,而是希望將其從5pt縮小到0pt,同時淡化不透明度。
創建圖形上下文,繪製圖形並捕獲圖像是實現此目的的一種非常昂貴的方式。我建議改爲使用UIView的自定義子類並重寫'drawRect'。然後,您可以直接在當前圖形上下文中執行繪圖命令。您可以在視圖上發出setNeedsDisplay以觸發視圖進行更新。您可能需要稍微增加筆劃寬度(嘗試大一點),而不是繪製階段。 –
@DuncanC謝謝你。是的,我剛剛意識到越來越多的筆畫寬度可以解決鬼紋問題。我會嘗試一下你的drawInRect建議。乾杯! – CaptainStiggz
擦除策略並不是一個好主意......如果您繪製一個新的線段穿越舊線路,並且舊線路被擦除,那麼新線路也會在交叉點處被擦除。 – spinalwrap