Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating pattern on-the-fly?

Is there a way to create a colored fill pattern dynamically in Cocoa?

In particular instead of using a fixed pattern from an image file via

NSColor *fillPattern = [NSColor colorWithPatternImage:patternImage];

I'd like to create a pattern by dynamically choosing the appropriate colors at runtime. Background is highlighting a colored object by rendering stripes or squares in the ''opposite'' color on top of it - whatever opposite might mean in this context, but that's a different story..

Being applied to potentially hundreds of objects in a drawing app it needs to be a rather fast method so I suppose just swapping colors in patternImage won't be good enough.

(It did work just fine back in QuickDraw..!)

like image 414
Jay Avatar asked Mar 28 '26 21:03

Jay


1 Answers

Why not just draw to an in-memory image and use that for your pattern?

NSImage* patternImage = [[NSImage alloc] initWithSize:someSize];
[patternImage lockFocus];
//draw your pattern
[patternImage unlockFocus];
NSColor* patternColor = [NSColor colorWithPatternImage:patternImage];
//do something with the pattern color
//remember to release patternImage if you're not using ARC

Performance-wise, you generally should be looking at optimising drawing by paying attention to the rect passed in to drawRect: and making sure you only draw what is necessary. If you do that then I can't see the pattern drawing performance being a major problem.

like image 103
Rob Keniger Avatar answered Apr 02 '26 03:04

Rob Keniger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!