中,每次调用drawMulticolorLine时都会看到一个绘制多色线的代码。
void drawMulticolorLine
{
CGContextBeginPath(secondaryContext);
CGContextMoveToPoint(secondaryContext, h, v);
for( int i = 1; i < lineWidth; ++ )
{
SetStrokeColor(i);
CGContextAddLineToPoint(secondaryContext, h+i, v);
CGContextDrawPath(secondaryContext, kCGPathFillStroke);
CGContextMoveToPoint(secondaryContext, h+i, v);
}
}
//a function that sets a different color for each i
void SetStrokeColor(int i)
{
CGContextSetRGBStrokeColor(secondaryContext,…
}
上面的代码可以工作,但如果我在现场使用它,它是一个性能杀手。所以我尝试使用下面的代码来提高绘图性能。
void drawMulticolorLine
{
CGContextBeginPath(secondaryContext);
CGContextMoveToPoint(secondaryContext, h, v);
for( int i = 1; i < lineWidth; ++ )
{
SetStrokeColor(i);
CGContextAddLineToPoint(secondaryContext, h+i, v);
}
CGContextDrawPath(secondaryContext, kCGPathFillStroke);
}
//a function that sets a different color for each i
void SetStrokeColor(int i)
{
CGContextSetRGBStrokeColor(secondaryContext,…
}
如果线条颜色始终相同,则此代码的效果会很好。
我现在的问题是,一旦调用CGContextDrawPath,整行就会以最后一个CGContextSetRGBStrokeColor的颜色绘制。
路径是否保留了添加的每个线段的颜色?
非常感谢任何帮助。
欢呼声, BZT
答案 0 :(得分:0)
最近在操场上玩,所以要共享源代码。
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
}
let copy: CGPath = ...
let image = UIGraphicsImageRenderer(size: copy.boundingBoxOfPath.size).image { context in
context.cgContext.setLineWidth(2)
copy.applyWithBlock { element in
switch element.pointee.type {
case .moveToPoint:
context.cgContext.move(to: element.pointee.points[0])
case .addLineToPoint:
context.cgContext.addLine(to: element.pointee.points[0])
context.cgContext.setStrokeColor(UIColor.random().cgColor)
context.cgContext.strokePath()
context.cgContext.move(to: element.pointee.points[0])
case .addQuadCurveToPoint:
let controlPoint = element.pointee.points[0]
let point = element.pointee.points[1]
context.cgContext.addCurve(to: point, control1: controlPoint, control2: controlPoint)
context.cgContext.setStrokeColor(UIColor.random().cgColor)
context.cgContext.strokePath()
context.cgContext.move(to: point)
case .addCurveToPoint:
let controlPoint1 = element.pointee.points[0]
let controlPoint2 = element.pointee.points[1]
let point = element.pointee.points[2]
context.cgContext.addCurve(to: point, control1: controlPoint1, control2: controlPoint2)
context.cgContext.setStrokeColor(UIColor.random().cgColor)
context.cgContext.strokePath()
context.cgContext.move(to: point)
case .closeSubpath:
context.cgContext.setStrokeColor(UIColor.random().cgColor)
context.cgContext.strokePath()
}
}
}