This guide provides comprehensive examples and usage patterns for the cggen Drawing API.
- Architecture Overview - Understanding cggen's structure
- API Design Considerations - Why the API works this way
- Path Generation - Extracting paths for custom rendering
// Direct usage as views
Drawing.circle
Drawing.square
Drawing.star// UIKit
let circleImage = UIImage(drawing: .circle)
let starImage = UIImage(drawing: .star, scale: 2.0)
// AppKit
let circleImage = NSImage(drawing: .circle)
let starImage = NSImage(drawing: .star, scale: 2.0)// UIKit
let circleImage = UIImage.draw(.circle)
let starImage = UIImage.draw(.star, scale: 2.0)
// AppKit
let circleImage = NSImage.draw(.circle)
let starImage = NSImage.draw(.star, scale: 2.0)The API includes comprehensive content mode support for generating images at specific sizes with different scaling behaviors.
public enum DrawingContentMode {
case scaleToFill // Stretches image to fill target size
case aspectFit // Scales to fit within target, maintaining aspect ratio
case aspectFill // Scales to fill target, maintaining aspect ratio
case center // Centers at original size
case top, bottom, left, right // Edge alignments
case topLeft, topRight, bottomLeft, bottomRight // Corner alignments
}// Create thumbnail with aspect fit (using initializer)
let thumbnail = UIImage(
drawing: .logo,
size: CGSize(width: 100, height: 100),
contentMode: .aspectFit
)
// Create banner with aspect fill (using static method)
let banner = UIImage.draw(
.banner,
size: CGSize(width: 320, height: 80),
contentMode: .aspectFill
)
// Create icon maintaining aspect ratio
let icon = NSImage(
drawing: .appIcon,
size: CGSize(width: 64, height: 64),
contentMode: .aspectFit
)let iconSizes = [16, 32, 64, 128, 256, 512, 1024]
let icons = iconSizes.map { size in
UIImage(
drawing: .appIcon,
size: CGSize(width: size, height: size),
contentMode: .aspectFit
)
}func createThumbnail(for drawing: Drawing, maxSize: CGFloat) -> UIImage {
UIImage(
drawing: drawing,
size: CGSize(width: maxSize, height: maxSize),
contentMode: .aspectFit
)
}// For a button with fixed size
let buttonIcon = UIImage(
drawing: .menuIcon,
size: button.bounds.size,
contentMode: .center
)
// For a banner view
let bannerImage = UIImage(
drawing: .headerGraphic,
size: bannerView.bounds.size,
contentMode: .aspectFill
)// Draw directly to a context
if let context = UIGraphicsGetCurrentContext() {
Drawing.circle.draw(context)
// Draw at specific position
context.draw(Drawing.star, at: CGPoint(x: 50, y: 50))
}- SwiftUI: All platforms supporting SwiftUI
- UIKit: iOS, tvOS, Mac Catalyst
- AppKit: macOS
- Core Graphics: All Apple platforms
- Images are rendered on-demand
- Use appropriate scale factors for target displays
- Content mode calculations are performed during image creation
- Generated code uses optimized bytecode for efficient drawing