我没有尝试此代码,但之前遇到了相同的情况,我通过执行以下操作解决了这个问题:
在使用-drawRect
中绘制这些模式并将其添加到您的CAShapeLayer
UIBezierPath
CustomView
layer
[self.layer addSubLayer:self.shapeLayer_main];
然后获取您希望使用绘制笔划的矩形框架
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
//Check in which rect in your view contains the touch location
//Then call the method to draw the stroke with the detected rect as the parameter
[self drawStrokeWithRect:touchedRect];
}
在方法中,
-(void)drawStrokeWithRect:(CGRect )touchedRect {
//Create a shapeLayer with desired strokeColor, lineWidth and path(A UIBezierPath)
//This is the layer your are going to animate
//Add this shapeLayer to your self.shapeLayer_main added to the customView's layer
CAShapeLayer * shapeLayer = [CAShapeLayer layer];
shapeLayer.lineWidth = 4;
shapeLayer.strokeColor = strokeColor.CGColor;
shapeLayer.fillColor = transparentColor.CGColor;
shapeLayer.path = [[UIBezierPath bezierPathWithRect:touchedRect]CGPath];
[self.shapeLayer_main addSublayer:shapeLayer];
//Adding Animation to the ShapeLayer
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration = 1.0;
drawAnimation.removedOnCompletion = NO;
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[shapeLayer addAnimation:drawAnimation forKey:@"StrokeAnimation"];
}
每次点击视图时,都会使用您在动画中提供的笔触颜色绘制一个矩形。