Domanda

I'm writing a Core Graphics Cross Plattform Library for OSX and iOS.

I'm porting it over from an existing iOS Project where I created the UIColor CGColorattribute. Of course UIColor is not available on the mac.

So whats the right way to use the same color on both systems? Should i get the rgb value of all previously used UIColors and create CGColors programmtically or should I divide the code with TARGET_OS_MAC and TARGET_OS_IPHONE ifdefs?

È stato utile?

Soluzione

My preferred approach is to avoid UIColor and NSColor altogether, and simply use CGColorRef wherever possible.

Core Animation is the best/most modern way to draw on both iOS and OS X. It expects CGColorRef objects and is (pretty much) cross platform.

The only drawback is, being a lower level data type, ARC doesn't handle memory management for you. But manual memory management isn't that hard.

Usage of CGColorRef:

CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componennts[4] = {255, 255, 255, 255}; // white, with 100% opacity. Use {0,0,0,255} for black, or {255,0,0,127.5} for red with 50% opacity.
CGColorRef color = CGColorCreate(colorSpace, componennts);
CGColorSpaceRelease(space);

layer.backgroundColor = color; // layer is a CALayer object
CGColorRelease(color);

You could avoid creating/releasing the color space object by storing it in a static variable:

static CGColorSpaceRef colorSpace;

@implementation MyClass

+ (void)initialize
{
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    colorSpace = CGColorSpaceCreateDeviceRGB();
  });
}

- (void)blah
{
    CGFloat componennts[4] = {255, 255, 255, 255}; // white, with 100% opacity. Use {0,0,0,255} for black, or {255,0,0,127.5} for red with 50% opacity.
    CGColorRef color = CGColorCreate(space, componennts);

    layer.backgroundColor = color; // layer is a CALayer object
    CGColorRelease(color);

Altri suggerimenti

I think you should do something like this:

#ifndef UIColor
#define UIColor NSColor
#endif

How about creating an alias on macOS

#if canImport(UIKit)
    import UIKit
#elseif canImport(AppKit)
    import AppKit

    public typealias UIColor = NSColor
#endif

public protocol Theme {
    var tint: UIColor { get }
    ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top