A Swift library that provides full API compatibility with Apple's CoreGraphics framework for WebAssembly (WASM) environments.
OpenCoreGraphics enables cross-platform Swift code to use CoreGraphics APIs in WASM environments where Apple's CoreGraphics is not available. The API is designed to be 100% compatible with CoreGraphics, allowing code to compile and work without modification.
Add OpenCoreGraphics to your Package.swift:
dependencies: [
.package(url: "https://github.com/1amageek/OpenCoreGraphics.git", from: "1.0.0")
]Then add it to your target:
.target(
name: "YourTarget",
dependencies: ["OpenCoreGraphics"]
)Use conditional imports to support both Apple platforms and WASM:
#if canImport(CoreGraphics)
import CoreGraphics
#else
import OpenCoreGraphics
#endif// Create a bitmap context
let context = CGContext(
data: nil,
width: 400,
height: 300,
bitsPerComponent: 8,
bytesPerRow: 400 * 4,
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
)!
// Draw shapes
context.setFillColor(CGColor(red: 1, green: 0, blue: 0, alpha: 1))
context.fill(CGRect(x: 50, y: 50, width: 100, height: 80))
context.setStrokeColor(CGColor(red: 0, green: 0, blue: 1, alpha: 1))
context.setLineWidth(3)
context.strokeEllipse(in: CGRect(x: 200, y: 50, width: 100, height: 100))
// Get the rendered image
let image = context.makeImage()let path = CGMutablePath()
path.move(to: CGPoint(x: 100, y: 100))
path.addLine(to: CGPoint(x: 200, y: 100))
path.addLine(to: CGPoint(x: 150, y: 200))
path.closeSubpath()
context.addPath(path)
context.setFillColor(.red)
context.fillPath()let gradient = CGGradient(
colorsSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
colors: [CGColor.red, CGColor.blue],
locations: [0, 1]
)!
context.drawLinearGradient(
gradient,
start: CGPoint(x: 0, y: 0),
end: CGPoint(x: 400, y: 300),
options: []
)context.saveGState()
context.translateBy(x: 200, y: 150)
context.rotate(by: .pi / 4)
context.scaleBy(x: 2, y: 2)
context.fill(CGRect(x: -25, y: -25, width: 50, height: 50))
context.restoreGState()On WASM, OpenCoreGraphics uses WebGPU for hardware-accelerated rendering. Call setupGraphicsContext() once at application startup to initialize WebGPU.
import OpenCoreGraphics
@main
struct MyApp {
static func main() async throws {
// Initialize WebGPU (call once at startup)
try await setupGraphicsContext()
// Now use CGContext normally
let context = CGContext(
data: nil,
width: 400,
height: 300,
bitsPerComponent: 8,
bytesPerRow: 400 * 4,
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
)!
context.setFillColor(CGColor(red: 1, green: 0, blue: 0, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: 100, height: 100))
// GPU readback
let image = await context.makeImageAsync()
}
}setupGraphicsContext() throws GraphicsContextError if initialization fails:
do {
try await setupGraphicsContext()
} catch GraphicsContextError.webGPUNotSupported {
// Browser doesn't support WebGPU
} catch GraphicsContextError.adapterNotAvailable {
// Failed to get WebGPU adapter
} catch GraphicsContextError.deviceNotAvailable {
// Failed to get WebGPU device
}WebGPU is required for WASM rendering. Supported browsers:
- Chrome 113+
- Edge 113+
- Firefox 139+ (with flags)
- Safari 18+ (macOS Sequoia / iOS 18)
CGFloat,CGPoint,CGSize,CGRect,CGVectorCGAffineTransform,CGAffineTransformComponents
CGContext,CGImage,CGPath,CGMutablePath,CGLayer
CGColor,CGColorSpace,CGColorSpaceModel,CGColorConversionInfoCGComponent,CGBitmapInfo,CGImageAlphaInfo
CGGradient,CGShading,CGPattern,CGFunction
CGDataProvider,CGDataConsumer
CGPDFDocument,CGPDFPage,CGPDFObject,CGPDFScanner
CGFont
CGBlendMode,CGTextDrawingMode,CGInterpolationQualityCGGradientDrawingOptions,CGPathFillRule,CGLineCap,CGLineJoin- And more...
# Build the package
swift build
# Run tests
swift test
# Build for WASM (requires Swift SDK for WASM)
swift build --swift-sdk <your-wasm-sdk>
# Example with specific SDK
swift build --swift-sdk swift-6.2.3-RELEASE_wasm# Install the Swift WASM SDK
swift sdk install https://github.com/aspect-build/aspect-wasm32-wasi-release/releases/latest/download/swift-wasm32-wasi.artifactbundle.zip
# List installed SDKs
swift sdk list- Swift 6.0+
- For WASM builds: Swift WASM SDK
This library is designed with WASM compatibility as a primary goal. All implementations use pure Swift types that work seamlessly in WebAssembly environments.
OpenCoreGraphics is built entirely with Swift standard types:
Stringfor names and identifiersDatafor binary data[String: Any]for property lists and dictionariesUIntfor type identifiers
All standard color space names are available as String constants:
CGColorSpace.sRGB // "kCGColorSpaceSRGB"
CGColorSpace.displayP3 // "kCGColorSpaceDisplayP3"
CGColorSpace.genericGrayGamma2_2 // "kCGColorSpaceGenericGrayGamma2_2"
CGColorSpace.genericCMYK // "kCGColorSpaceGenericCMYK"
// ... and many more- Full API Compatibility: Identical type names, method signatures, and property names as CoreGraphics
- WASM First: Uses pure Swift types that work in WebAssembly environments
- Same Behavior: Consistent semantics with Apple's implementation
- Modern Swift: All value types are
@frozenand conform toSendable,Hashable,Equatable, andCodable - No Deprecated APIs: Only current, non-deprecated CoreGraphics APIs are implemented
- Performance Optimized: Uses
@inlinablefor performance-critical methods
All geometric value types (CGFloat, CGPoint, CGSize, CGRect, CGVector, CGAffineTransform) conform to:
Sendable- Thread-safeHashable- Can be used in Sets and as Dictionary keysEquatable- Equality comparisonCodable- JSON serialization support
Additionally, CGFloat conforms to all numeric protocols:
FloatingPoint,BinaryFloatingPointSignedNumeric,NumericComparable,Strideable
MIT License