Search code examples
iphoneiosquartz-graphicsuicolor

Get size of repeated pattern from UIColor?


I can query if a UIColor is a pattern by inspecting the CGColor instance it wraps, the CGColorGetPattern() function returns the pattern if it exist, or null if it is not a pattern color.

CGPatternCreate() method requires a bounds when creating a pattern, this value defines the size of the pattern tile (Known as cell in Quartz parlance).

How would I go about to retrieve this pattern size from a UIColor, or the backing CGPattern once it has been created?


Solution

  • If your application is intended for internal distribution only, then you can use a private API. If you look at the functions defined in the CoreGraphics framework, you will see that there is a bunch of functions and among them one called CGPatternGetBounds:

    otool -tV /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics | egrep "^_CGPattern"
    

    You just have to make some function lookup on the framework and use it through a function pointer.

    The header to include:

    #include <dlfcn.h>
    

    The function pointer:

    typedef CGRect (*CGPatternGetBounds)(CGPatternRef pattern);
    

    The code to retrieve the function:

    void *handle = dlopen("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", RTLD_NOW);
    CGPatternGetBounds getBounds = (CGPatternGetBounds) dlsym(handle, "CGPatternGetBounds");
    

    The code to retrieve the bounds:

    UIColor *uicolor = [UIColor groupTableViewBackgroundColor]; // Select a pattern color
    CGColorRef color = [uicolor CGColor];
    CGPatternRef pattern = CGColorGetPattern(color);
    CGRect bounds = getBounds (pattern); // This result is a CGRect(0, 0, 84, 1)