IluTov
IluTov

Reputation: 6852

Drawing a vector path with a custom style

I was very surprised to not find the answer on Stackoverflow to this one.

I have a vector path in pdf format, like Safari or the Mac App Store apps usually use as image icons.

Now, I'd like to specify the fill-color and a custom shadow in code, rather than making images and exporting them. I didn't figure out how to do this.

The shadow works, however the fill color does not.
Can anyone tell me how to do this?


Current Code

[NSGraphicsContext saveGraphicsState];
{
    // Has no effect
    [[NSColor colorWithCalibratedRed:0.92f green:0.97f blue:0.98f alpha:1.00f] setFill];
    // Neither has this
    [[NSColor colorWithCalibratedRed:0.92f green:0.97f blue:0.98f alpha:1.00f] set];

    NSShadow *shadow = [NSShadow new];
    [shadow setShadowOffset:NSMakeSize(0, -1)];
    [shadow setShadowColor:[NSColor blackColor]];
    [shadow setShadowBlurRadius:3.0];
    [shadow set];

    [image drawInRect:imgRect 
             fromRect:NSZeroRect 
            operation:NSCompositeXOR 
             fraction:1.0 
       respectFlipped:YES 
                hints:nil];
}
[NSGraphicsContext restoreGraphicsState];

Upvotes: 0

Views: 128

Answers (1)

ipmcc
ipmcc

Reputation: 29886

In terms of calling drawInRect:... the image "is what it is". Setting the fill and stroke will effect only primitive operations. A good way to think about this is to realize that all images, vector or raster, have to behave the same way; It would be weird for the current fill color that's set on the context to affect the drawing of a raster-based image, right? Same idea -- the image is the image. The vector image might also have multiple paths in it, each with different fills. It wouldn't make sense for those to be overridden by the fill color set on the context either.

The shadow works regardless because it's effectively a compositing operation; Drawing a given image with a given shadow setting produces the same shadow whether the image was raster-based or the vector equivalent thereof.

In short, if you want to change the contents of the image, you're going to have to write the code to extract the vectors from the image and then draw them as primitives.

Alternately, if all you want is to fill any filled areas with the color, you could use the vector image to create a mask on the context, then you could set the color on the context, and fill. That might produce the desired effect.

Upvotes: 1

Related Questions