infiniteLoop
infiniteLoop

Reputation: 2183

UIBezierPath slow performance if used along with CGContextSetShadowWithColor

I am developing an app in which user draws lines with finger touch or simply sprays colors. I am using UIBezierPath to paint the path (colors) on finger touch in drawRect method with following code.

CGContextRef context = UIGraphicsGetCurrentContext();

for (BezierPath *path in paths)
{
    path.path.lineWidth = [DataController dataController].apertureRadius * 2;
    path.path.lineJoinStyle = kCGLineJoinRound;
    path.path.lineCapStyle = kCGLineCapRound;
    ///
    [path.color set];
    CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 20, [path.color CGColor]);//Problem
    //

    [path.path stroke];
}

This code works perfect on simulator but on Device the spray is really slow. and the problem is only with method call CGContextSetShadowWithColor, if I comment this line performance is best with no problem at all.

Please suggest me why this is so and what should I do. This line is necessary as I want to show the spray like effect with Blurry shadow.

Upvotes: 1

Views: 1835

Answers (1)

rob mayoff
rob mayoff

Reputation: 385600

Drawing a shadow can be slow. The system has to draw your path to an off-screen buffer, compute a Gaussian blur of the off-screen buffer's alpha channel to another off-screen buffer, then composite the two off-screen buffers into the original graphics context.

I suspect that every time a touch is updated, you're redrawing the entire path that the touch has followed. You need to draw as little as possible on each frame.

Keep your own bitmap context (created with either CGBitmapContextCreate or UIGraphicsBeginImageContextWithOptions). Draw to this private context. When you get a touch moved event, only draw the stroke from the touch's old location to the new location. Then get an image from the bitmap context (using either CGBitmapContextCreateImage or UIGraphicsGetImageFromCurrentImageContext) and set it as your view's image or your layer's contents.

Upvotes: 1

Related Questions