From c710441ff616a82b1549c418251ed42a7e106855 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 1/7] Named Silica's types that AndroidGraphics and Foundation also have, in AndroidSilica --- Sources/AndroidSilica/Export.swift | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/Sources/AndroidSilica/Export.swift b/Sources/AndroidSilica/Export.swift index 32f0bbe..9ea3f15 100644 --- a/Sources/AndroidSilica/Export.swift +++ b/Sources/AndroidSilica/Export.swift @@ -8,19 +8,13 @@ @_exported import Silica -#if canImport(AndroidGraphics) - -// These module-local aliases resolve every unqualified reference to Silica's types; -// Android's types are referenced fully qualified (e.g. `AndroidGraphics.Canvas`). -public typealias CGContext = Silica.CGContext -public typealias CGColor = Silica.CGColor -public typealias CGPath = Silica.CGPath -public typealias CGFont = Silica.CGFont -public typealias CGImage = Silica.CGImage -public typealias CGGlyph = Silica.CGGlyph -public typealias CGLineCap = Silica.CGLineCap -public typealias CGLineJoin = Silica.CGLineJoin -public typealias CGTextDrawingMode = Silica.CGTextDrawingMode -public typealias PathElement = Silica.PathElement - -#endif +// AndroidGraphics and Foundation have types of the same names: in this module +// the names are Silica's, and Android's are written in full +// (`AndroidGraphics.Path`). +typealias Point = Silica.Point +typealias Rect = Silica.Rect +typealias Color = Silica.Color +typealias Path = Silica.Path +typealias Font = Silica.Font +typealias BlendMode = Silica.BlendMode +typealias AffineTransform = Silica.AffineTransform From ae7117c851b20e8038b137355c5e75c7a780335f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 2/7] Made the Android font handle a FontFace --- Sources/AndroidSilica/AndroidFontHandle.swift | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Sources/AndroidSilica/AndroidFontHandle.swift b/Sources/AndroidSilica/AndroidFontHandle.swift index 1a2fb12..a7da87f 100644 --- a/Sources/AndroidSilica/AndroidFontHandle.swift +++ b/Sources/AndroidSilica/AndroidFontHandle.swift @@ -22,12 +22,12 @@ import Silica /// - Note: `Typeface.create` falls back to the system default for unknown /// family names (matching FontConfig's fuzzy behavior on Linux), so font /// creation does not fail for unrecognized names. -public final class AndroidFontHandle: CGFontHandle { +public final class AndroidFontHandle: Silica.FontFace { // MARK: - Constants /// Nominal em size used for measuring (Android exposes no font-unit metrics). - internal static let nominalSize: CGFloat = 2048 + internal static let nominalSize: Double = 2048 // MARK: - Properties @@ -40,10 +40,10 @@ public final class AndroidFontHandle: CGFontHandle { /// Paint configured at the nominal size, used for measuring and shaping. private let measuringPaint: Paint - private let internalMetrics: (ascent: CGFloat, descent: CGFloat, capHeight: CGFloat) + private let internalMetrics: (ascent: Double, descent: Double, capHeight: Double) /// Shaped glyph information, populated by `glyph(for:)`. - private var glyphCache = [Silica.CGGlyph: (advance: CGFloat, font: AndroidGraphics.Font?)]() + private var glyphCache = [Glyph: (advance: Double, font: AndroidGraphics.Font?)]() /// The font of the first shaped glyph, used as a fallback for `Canvas.drawGlyphs`. internal private(set) var baseFont: AndroidGraphics.Font? @@ -96,31 +96,31 @@ public final class AndroidFontHandle: CGFontHandle { else { return nil } // FontMetrics.ascent is negative above the baseline; descent positive below. - let ascent = CGFloat(-fontMetrics.ascent) / AndroidFontHandle.nominalSize - let descent = CGFloat(-fontMetrics.descent) / AndroidFontHandle.nominalSize + let ascent = Double(-fontMetrics.ascent) / AndroidFontHandle.nominalSize + let descent = Double(-fontMetrics.descent) / AndroidFontHandle.nominalSize // approximate the cap height from the bounds of an uppercase letter - let bounds = Rect() + let bounds = AndroidGraphics.Rect() paint.getTextBounds("H", 0, 1, bounds) - let capHeight = CGFloat(bounds.height()) / AndroidFontHandle.nominalSize + let capHeight = Double(bounds.height()) / AndroidFontHandle.nominalSize self.internalMetrics = (ascent: ascent, descent: descent, capHeight: capHeight) } - // MARK: - CGFontHandle + // MARK: - FontFace /// The family name (Android exposes no full font name). public var fullName: String { familyName } public var unitsPerEm: Int { Int(AndroidFontHandle.nominalSize) } - public var ascent: CGFloat { internalMetrics.ascent } + public var ascent: Double { internalMetrics.ascent } - public var descent: CGFloat { internalMetrics.descent } + public var descent: Double { internalMetrics.descent } - public var capHeight: CGFloat { internalMetrics.capHeight } + public var capHeight: Double { internalMetrics.capHeight } - public func glyph(for scalar: Unicode.Scalar) -> Silica.CGGlyph { + public func glyph(for scalar: Unicode.Scalar) -> Glyph { let characters = Array(String(scalar).utf16) @@ -131,13 +131,13 @@ public final class AndroidFontHandle: CGFontHandle { shaped.glyphCount() > 0 else { return 0 } - let glyph = Silica.CGGlyph(truncatingIfNeeded: shaped.getGlyphId(0)) + let glyph = Glyph(truncatingIfNeeded: shaped.getGlyphId(0)) if glyphCache[glyph] == nil { let font = shaped.getFont(0) - glyphCache[glyph] = (advance: CGFloat(shaped.getAdvance()) / AndroidFontHandle.nominalSize, + glyphCache[glyph] = (advance: Double(shaped.getAdvance()) / AndroidFontHandle.nominalSize, font: font) if baseFont == nil { @@ -152,7 +152,7 @@ public final class AndroidFontHandle: CGFontHandle { /// /// Android exposes no advance lookup by glyph index; advances are memoized /// when glyphs are shaped via `glyph(for:)`. Unknown glyph indices report 0. - public func advances(for glyphs: [Silica.CGGlyph]) -> [CGFloat] { + public func advances(for glyphs: [Glyph]) -> [Double] { return glyphs.map { glyphCache[$0]?.advance ?? 0 } } @@ -160,7 +160,7 @@ public final class AndroidFontHandle: CGFontHandle { // MARK: - Internal Methods /// The `android.graphics.fonts.Font` for a previously shaped glyph. - internal func font(for glyph: Silica.CGGlyph) -> AndroidGraphics.Font? { + internal func font(for glyph: Glyph) -> AndroidGraphics.Font? { return glyphCache[glyph]?.font } From 7c1bb29a672871b5bf13f3dd18249a9fa2b2cd16 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 3/7] Registered the Android backend with bitmap renderers and font faces --- Sources/AndroidSilica/AndroidBackend.swift | 52 +++++++++------------- 1 file changed, 20 insertions(+), 32 deletions(-) diff --git a/Sources/AndroidSilica/AndroidBackend.swift b/Sources/AndroidSilica/AndroidBackend.swift index eedad86..7d7c4c4 100644 --- a/Sources/AndroidSilica/AndroidBackend.swift +++ b/Sources/AndroidSilica/AndroidBackend.swift @@ -16,64 +16,52 @@ import Foundation import Silica /// Android Canvas rendering backend. +/// The Android rendering backend: fonts from `Typeface`, PNG codecs from +/// `BitmapFactory` and `Bitmap`, and bitmaps drawn with `Canvas`. public enum AndroidBackend: SilicaBackendProtocol { - /// Registers Android as the default rendering backend. + /// Makes Android the default rendering backend. public static func register() { - - SilicaBackend.default = AndroidBackend.self + SilicaBackend.register(AndroidBackend.self, name: "Android") } internal static func registerIfNeeded() { - - guard SilicaBackend.default == nil else { return } - register() + SilicaBackend.registerIfNeeded(AndroidBackend.self, name: "Android") } // MARK: - SilicaBackendProtocol - public static func font(named name: String) -> Silica.CGFont? { - - guard let handle = AndroidFontHandle(name: name) - else { return nil } - - return Silica.CGFont(name: name, family: handle.familyName, handle: handle) + public static func fontFace(named name: String) -> (any Silica.FontFace)? { + AndroidFontHandle(name: name) } - public static func decodePNG(_ data: Data) -> Silica.CGImage? { - + public static func decodePNG(_ data: Data) -> Silica.Image? { let bytes = data.map { Int8(bitPattern: $0) } - guard let factoryClass = try? JavaClass(), let bitmap = factoryClass.decodeByteArray(bytes, 0, Int32(bytes.count)) else { return nil } - - return Silica.CGImage(bitmap) + return Silica.Image(bitmap) } - public static func encodePNG(_ image: Silica.CGImage) -> Data? { - - guard let bitmap = image.toAndroidBitmap() - else { return nil } - + public static func encodePNG(_ image: Silica.Image) -> Data? { + guard let bitmap = image.toAndroidBitmap() else { return nil } let stream = ByteArrayOutputStream() - - guard bitmap.compress(Bitmap.CompressFormat(.PNG), 100, stream) - else { return nil } - + guard bitmap.compress(Bitmap.CompressFormat(.PNG), 100, stream) else { return nil } let bytes = stream.toByteArray() - return Data(bytes.map { UInt8(bitPattern: $0) }) } + + public static func makeBitmapRenderer(size: Silica.Size, scale: Double) -> (any Renderer)? { + try? AndroidCanvasRenderer(bitmap: size, scale: scale) + } } -// MARK: - CGImage Conversion -public extension Silica.CGImage { +public extension Silica.Image { - /// Creates a Silica bitmap image from an Android bitmap, + /// An image of an Android bitmap's pixels, /// normalizing the pixel format to premultiplied RGBA. - convenience init?(_ bitmap: AndroidGraphics.Bitmap) { + convenience init?(_ bitmap: AndroidGraphics.Bitmap, scale: Double = 1) { let width = Int(bitmap.getWidth()) let height = Int(bitmap.getHeight()) @@ -114,7 +102,7 @@ public extension Silica.CGImage { } } - self.init(width: width, height: height, bytesPerRow: bytesPerRow, data: data) + self.init(width: width, height: height, bytesPerRow: bytesPerRow, data: data, scale: scale) } /// Converts to an Android bitmap (`ARGB_8888`). From a6f053f30c660d5dc76229be9061c31b7b8d1058 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 4/7] Drew Silica's Renderer commands with Canvas, in AndroidCanvasRenderer --- .../AndroidSilica/AndroidCanvasContext.swift | 898 ------------------ .../AndroidSilica/AndroidCanvasRenderer.swift | 516 ++++++++++ 2 files changed, 516 insertions(+), 898 deletions(-) delete mode 100644 Sources/AndroidSilica/AndroidCanvasContext.swift create mode 100644 Sources/AndroidSilica/AndroidCanvasRenderer.swift diff --git a/Sources/AndroidSilica/AndroidCanvasContext.swift b/Sources/AndroidSilica/AndroidCanvasContext.swift deleted file mode 100644 index 949759a..0000000 --- a/Sources/AndroidSilica/AndroidCanvasContext.swift +++ /dev/null @@ -1,898 +0,0 @@ -// -// AndroidCanvasContext.swift -// AndroidSilica -// -// Created by Alsey Coleman Miller on 7/13/26. -// Copyright © 2026 PureSwift. All rights reserved. -// - -#if canImport(AndroidGraphics) - -import AndroidGraphics -import SwiftJava -import JavaIO -import JavaLangIO -import Foundation -import Silica - -/// Android Canvas backed implementation of `CGContext`. -/// -/// Android's Canvas is already a top-left origin, y-down coordinate system, so no -/// base flip is required. PDF output uses `android.graphics.pdf.PdfDocument`, -/// whose page canvas operates in points (1/72 inch). -/// -/// The current transformation matrix is tracked on the Swift side: path points are -/// transformed into device space at add time (matching Cairo and Quartz semantics) -/// and strokes are rendered under the CTM so pen geometry transforms correctly. -/// -/// - Note: `finish()` is mandatory for PDF destinations — the document is only -/// written to disk when it is called. JNI-backed objects must be used from a -/// JVM-attached thread; a context should be created, used and finished on the -/// same thread. -/// - Note: Glyph rendering requires Android API 31 (`Canvas.drawGlyphs`). -public final class AndroidCanvasContext: Silica.CGContext { - - // MARK: - Properties - - public let size: CGSize - - /// Android's Canvas is natively top-left origin, y-down. - public var isFlipped: Bool { true } - - /// The underlying Android canvas (replaced on `beginPage()` for PDF destinations). - public private(set) var canvas: AndroidGraphics.Canvas - - public var textMatrix = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) - - // MARK: - Private Properties - - private let pdfDocument: PdfDocument? - - private let pdfURL: URL? - - private let bitmap: AndroidGraphics.Bitmap? - - private var page: PdfDocument.Page? - - private var pageNumber: Int32 = 0 - - private var isFinished = false - - private var internalState: State = State() - - private var devicePath = AndroidGraphics.Path() - - /// Mirror of the current path (device space) for the `path` accessor. - private var deviceElements = [PathElement]() - - private var deviceCurrentPoint: CGPoint? - - private var deviceSubpathStart: CGPoint? - - private var saveCounts = [Int32]() - - private var layerCounts = [Int32]() - - // MARK: - Initialization - - /// Creates a PDF drawing destination at the specified file URL. - /// - /// Call `finish()` to write the document to disk. - public init(pdf url: URL, size: CGSize) throws(SilicaError) { - - let document = PdfDocument() - - self.pdfDocument = document - self.pdfURL = url - self.bitmap = nil - self.size = size - - let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), 1).create() - - guard let page = document.startPage(info), - let canvas = page.getCanvas() - else { throw SilicaError.invalidContext } - - self.page = page - self.canvas = canvas - self.pageNumber = 1 - - AndroidBackend.registerIfNeeded() - } - - /// Creates a bitmap drawing destination of the specified size. - public init(bitmap size: CGSize) throws(SilicaError) { - - guard let bitmapClass = try? JavaClass(), - let bitmap = bitmapClass.createBitmap(Int32(size.width), Int32(size.height), Bitmap.Config(.ARGB_8888)) - else { throw SilicaError.noMemory } - - self.pdfDocument = nil - self.pdfURL = nil - self.bitmap = bitmap - self.size = size - self.canvas = Canvas(bitmap) - - AndroidBackend.registerIfNeeded() - } - - /// Wraps an existing canvas (e.g. provided to `View.onDraw`). - public init(canvas: AndroidGraphics.Canvas, size: CGSize) { - - self.pdfDocument = nil - self.pdfURL = nil - self.bitmap = nil - self.size = size - self.canvas = canvas - - AndroidBackend.registerIfNeeded() - } - - // MARK: - Defining Pages - - public func beginPage() { - - guard let document = pdfDocument, isFinished == false - else { return } - - if page != nil { - endPage() - } - - pageNumber += 1 - - let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), pageNumber).create() - - guard let newPage = document.startPage(info), - let newCanvas = newPage.getCanvas() - else { assertionFailure("Unable to start PDF page"); return } - - page = newPage - canvas = newCanvas - saveCounts.removeAll() - layerCounts.removeAll() - } - - public func endPage() { - - guard let document = pdfDocument, let openPage = page - else { return } - - document.finishPage(openPage) - page = nil - } - - /// Writes the PDF document to disk and closes it. - /// - /// This method is mandatory for PDF destinations. - public func finish() throws(SilicaError) { - - guard isFinished == false - else { return } - - defer { isFinished = true } - - guard let document = pdfDocument, let url = pdfURL - else { return } - - if page != nil { - endPage() - } - - let stream: FileOutputStream - - do { - stream = try FileOutputStream(url.path) - } - catch { - throw SilicaError.writeError - } - - do { - try document.writeTo(stream) - try stream.close() - } - catch { - throw SilicaError.writeError - } - - document.close() - } - - // MARK: - Transforming the Coordinate Space - - public var currentTransform: CGAffineTransform { - - return internalState.ctm - } - - public func scaleBy(x: CGFloat, y: CGFloat) { - - concatenate(CGAffineTransform(a: x, b: 0, c: 0, d: y, tx: 0, ty: 0)) - } - - public func translateBy(x: CGFloat, y: CGFloat) { - - concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: x, ty: y)) - } - - public func rotateBy(_ angle: CGFloat) { - - let cosine = cos(angle) - let sine = sin(angle) - - concatenate(CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: 0, ty: 0)) - } - - public func concatenate(_ transform: CGAffineTransform) { - - // new = transform * ctm (transform applied first, in user space) - internalState.ctm = transform.multiplied(by: internalState.ctm) - } - - // MARK: - Saving and Restoring the Graphics State - - public func save() throws(SilicaError) { - - saveCounts.append(canvas.save()) - - let newState = internalState.copy - newState.next = internalState - internalState = newState - } - - public func restore() throws(SilicaError) { - - guard let restoredState = internalState.next, - let saveCount = saveCounts.popLast() - else { throw .invalidRestore } - - canvas.restoreToCount(saveCount) - internalState = restoredState - } - - // MARK: - Graphics State Attributes - - public var shouldAntialias: Bool { - - get { return internalState.shouldAntialias } - - set { internalState.shouldAntialias = newValue } - } - - public var lineWidth: CGFloat { - - get { return internalState.lineWidth } - - set { internalState.lineWidth = newValue } - } - - public var lineJoin: CGLineJoin { - - get { return internalState.lineJoin } - - set { internalState.lineJoin = newValue } - } - - public var lineCap: CGLineCap { - - get { return internalState.lineCap } - - set { internalState.lineCap = newValue } - } - - public var miterLimit: CGFloat { - - get { return internalState.miterLimit } - - set { internalState.miterLimit = newValue } - } - - public var lineDash: (phase: CGFloat, lengths: [CGFloat]) { - - get { return internalState.lineDash } - - set { internalState.lineDash = newValue } - } - - public var tolerance: CGFloat { - - get { return internalState.tolerance } - - set { internalState.tolerance = newValue } - } - - public var fillColor: CGColor { - - get { return internalState.fill ?? CGColor.black } - - set { internalState.fill = newValue } - } - - public var strokeColor: CGColor { - - get { return internalState.stroke ?? CGColor.black } - - set { internalState.stroke = newValue } - } - - public var alpha: CGFloat { - - get { return internalState.alpha } - - set { - - internalState.alpha = newValue - - // match the Cairo backend: setting alpha overwrites the color alpha - internalState.fill?.alpha = newValue - internalState.stroke?.alpha = newValue - } - } - - public func setShadow(offset: CGSize, radius: CGFloat, color: CGColor) { - - internalState.shadow = (offset: offset, radius: radius, color: color) - } - - // MARK: - Constructing Paths - - public var path: CGPath { - - let inverse = internalState.ctm.inverse - - return CGPath(elements: deviceElements.map { $0.applying(inverse) }) - } - - public var currentPoint: CGPoint? { - - guard let devicePoint = deviceCurrentPoint - else { return nil } - - return devicePoint.applying(internalState.ctm.inverse) - } - - public func beginPath() { - - devicePath.reset() - deviceElements.removeAll() - deviceCurrentPoint = nil - deviceSubpathStart = nil - } - - public func closePath() { - - devicePath.close() - deviceElements.append(.closeSubpath) - deviceCurrentPoint = deviceSubpathStart - } - - public func move(to point: CGPoint) { - - let device = point.applying(internalState.ctm) - - devicePath.moveTo(Float(device.x), Float(device.y)) - deviceElements.append(.moveToPoint(device)) - deviceCurrentPoint = device - deviceSubpathStart = device - } - - public func addLine(to point: CGPoint) { - - let device = point.applying(internalState.ctm) - - devicePath.lineTo(Float(device.x), Float(device.y)) - deviceElements.append(.addLineToPoint(device)) - deviceCurrentPoint = device - } - - public func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint) { - - let deviceControl1 = control1.applying(internalState.ctm) - let deviceControl2 = control2.applying(internalState.ctm) - let deviceEnd = end.applying(internalState.ctm) - - devicePath.cubicTo(Float(deviceControl1.x), Float(deviceControl1.y), - Float(deviceControl2.x), Float(deviceControl2.y), - Float(deviceEnd.x), Float(deviceEnd.y)) - deviceElements.append(.addCurveToPoint(deviceControl1, deviceControl2, deviceEnd)) - deviceCurrentPoint = deviceEnd - } - - public func addArc(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { - - // Match Cairo's angle normalization: arcs sweep from the start angle to the - // end angle in increasing direction (decreasing when clockwise). - let start = Double(startAngle) - var end = Double(endAngle) - - if clockwise { - while end > start { end -= 2.0 * .pi } - } else { - while end < start { end += 2.0 * .pi } - } - - let radius = Double(radius) - - func point(at angle: Double) -> CGPoint { - return CGPoint(x: center.x + CGFloat(radius * Foundation.cos(angle)), - y: center.y + CGFloat(radius * Foundation.sin(angle))) - } - - let startPoint = point(at: start) - - // Cairo adds a line from the current point to the arc start (or moves to it). - if deviceCurrentPoint != nil { - addLine(to: startPoint) - } else { - move(to: startPoint) - } - - let total = end - start - - guard total != 0, radius > 0 - else { return } - - // subdivide into segments of at most 90°, lowered to cubic Béziers - let segments = max(1, Int((abs(total) / (Double.pi / 2.0)).rounded(.up))) - let delta = total / Double(segments) - let k = (4.0 / 3.0) * Foundation.tan(delta / 4.0) - - var angle1 = start - - for _ in 0 ..< segments { - - let angle2 = angle1 + delta - - let p1 = point(at: angle1) - let p2 = point(at: angle2) - - let control1 = CGPoint(x: p1.x - CGFloat(k * radius * Foundation.sin(angle1)), - y: p1.y + CGFloat(k * radius * Foundation.cos(angle1))) - let control2 = CGPoint(x: p2.x + CGFloat(k * radius * Foundation.sin(angle2)), - y: p2.y - CGFloat(k * radius * Foundation.cos(angle2))) - - addCurve(to: p2, control1: control1, control2: control2) - - angle1 = angle2 - } - } - - public func addRect(_ rect: CGRect) { - - move(to: CGPoint(x: rect.minX, y: rect.minY)) - addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) - addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) - addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) - closePath() - } - - // MARK: - Painting Paths - - public func strokePath() { - - if let shadow = internalState.shadow { - drawShadow(shadow) { canvas, paint in - self.strokeUnderTransform(paint: paint, canvas: canvas) - } - } - - strokeUnderTransform(paint: strokePaint(), canvas: canvas) - resetPath() - } - - public func fillPath(evenOdd: Bool, preserve: Bool) { - - devicePath.setFillType(Path.FillType(evenOdd ? .EVEN_ODD : .WINDING)) - - if let shadow = internalState.shadow { - drawShadow(shadow) { canvas, paint in - canvas.drawPath(self.devicePath, paint) - } - } - - canvas.drawPath(devicePath, fillPaint()) - - if preserve == false { - resetPath() - } - } - - public func clear() { - - clip(evenOdd: false) - } - - public func clip(evenOdd: Bool) { - - devicePath.setFillType(Path.FillType(evenOdd ? .EVEN_ODD : .WINDING)) - _ = canvas.clipPath(devicePath) - resetPath() - } - - // MARK: - Transparency Layers - - public func beginTransparencyLayer(in rect: CGRect?, auxiliaryInfo: CGAuxiliaryInfo?) { - - let alpha = Int32((internalState.alpha * 255).rounded()) - - let count: Int32 - - if let rect = rect { - // transform the user-space rect corners into device space and take their bounds - let corners = [ - CGPoint(x: rect.minX, y: rect.minY).applying(internalState.ctm), - CGPoint(x: rect.maxX, y: rect.minY).applying(internalState.ctm), - CGPoint(x: rect.minX, y: rect.maxY).applying(internalState.ctm), - CGPoint(x: rect.maxX, y: rect.maxY).applying(internalState.ctm) - ] - let minX = corners.map { $0.x }.min()! - let minY = corners.map { $0.y }.min()! - let maxX = corners.map { $0.x }.max()! - let maxY = corners.map { $0.y }.max()! - let bounds = RectF(Float(minX), Float(minY), Float(maxX), Float(maxY)) - count = canvas.saveLayerAlpha(bounds, alpha) - } else { - count = canvas.saveLayerAlpha(nil, alpha) - } - - layerCounts.append(count) - - let newState = internalState.copy - newState.next = internalState - newState.alpha = 1.0 - newState.shadow = nil - internalState = newState - } - - public func endTransparencyLayer() { - - guard let count = layerCounts.popLast() - else { return } - - canvas.restoreToCount(count) - - if let restoredState = internalState.next { - internalState = restoredState - } - } - - // MARK: - Drawing Images - - public func draw(_ image: CGImage, in rect: CGRect) { - - guard let bitmap = image.toAndroidBitmap() - else { assertionFailure("Unable to convert image"); return } - - // Silica's `draw(_:in:)` follows Apple's y-up image convention (callers - // flip the CTM to draw upright, as UIKit code does), so mirror the image - // vertically about the rect's centerline. - _ = canvas.save() - canvas.concat(internalState.ctm.toAndroid()) - canvas.translate(0, Float(rect.minY + rect.maxY)) - canvas.scale(1, -1) - - let destination = RectF(Float(rect.minX), Float(rect.minY), Float(rect.maxX), Float(rect.maxY)) - let paint = Paint() - paint.setAntiAlias(internalState.shouldAntialias) - canvas.drawBitmap(bitmap, nil, destination, paint) - - canvas.restore() - } - - // MARK: - Drawing Text - - public var font: CGFont? { - - return internalState.font - } - - public func setFont(_ font: CGFont) { - - internalState.font = font - } - - public var fontSize: CGFloat { - - get { return internalState.fontSize } - - set { internalState.fontSize = newValue } - } - - public var characterSpacing: CGFloat { - - get { return internalState.characterSpacing } - - set { internalState.characterSpacing = newValue } - } - - public var textDrawingMode: CGTextDrawingMode { - - get { return internalState.textMode } - - set { internalState.textMode = newValue } - } - - /// Primitive glyph rendering; positions are user-space baseline origins. - /// - /// Requires Android API 31 (`Canvas.drawGlyphs`). The linear components of the - /// text matrix (scale / rotation of glyph shapes) are not supported on Android. - public func draw(glyphs: [(glyph: CGGlyph, position: CGPoint)]) { - - guard let font = internalState.font, - fontSize > 0.0 && glyphs.isEmpty == false - else { return } - - guard let handle = font.handle as? AndroidFontHandle - else { assertionFailure("Font \(font.name) was not loaded by the Android backend"); return } - - guard internalState.textMode != .invisible - else { return } - - let paint = Paint() - paint.setAntiAlias(internalState.shouldAntialias) - paint.setColor(colorValue(internalState.fill ?? .black)) - paint.setTextSize(Float(fontSize)) - - switch internalState.textMode { - case .stroke, .strokeClip: - paint.setStyle(Paint.Style(.STROKE)) - paint.setColor(colorValue(internalState.stroke ?? .black)) - paint.setStrokeWidth(Float(internalState.lineWidth)) - case .fillStroke, .fillStrokeClip: - paint.setStyle(Paint.Style(.FILL_AND_STROKE)) - paint.setStrokeWidth(Float(internalState.lineWidth)) - default: - paint.setStyle(Paint.Style(.FILL)) - } - - _ = canvas.save() - canvas.concat(internalState.ctm.toAndroid()) - - for element in glyphs { - - let glyphFont = handle.font(for: element.glyph) ?? handle.baseFont - - canvas.drawGlyphs([Int32(element.glyph)], 0, - [Float(element.position.x), Float(element.position.y)], 0, - 1, glyphFont, paint) - } - - canvas.restore() - } - - // MARK: - Bitmap Contexts - - public func makeImage() -> CGImage? { - - guard let bitmap = self.bitmap - else { return nil } - - return CGImage(bitmap) - } - - // MARK: - Private Methods - - private func resetPath() { - - beginPath() - } - - private func fillPaint() -> Paint { - - let paint = Paint() - paint.setAntiAlias(internalState.shouldAntialias) - paint.setStyle(Paint.Style(.FILL)) - paint.setColor(colorValue(internalState.fill ?? .black)) - return paint - } - - private func strokePaint() -> Paint { - - let paint = Paint() - paint.setAntiAlias(internalState.shouldAntialias) - paint.setStyle(Paint.Style(.STROKE)) - paint.setColor(colorValue(internalState.stroke ?? .black)) - paint.setStrokeWidth(Float(internalState.lineWidth)) - paint.setStrokeMiter(Float(internalState.miterLimit)) - - switch internalState.lineCap { - case .butt: paint.setStrokeCap(Paint.Cap(.BUTT)) - case .round: paint.setStrokeCap(Paint.Cap(.ROUND)) - case .square: paint.setStrokeCap(Paint.Cap(.SQUARE)) - } - - switch internalState.lineJoin { - case .miter: paint.setStrokeJoin(Paint.Join(.MITER)) - case .round: paint.setStrokeJoin(Paint.Join(.ROUND)) - case .bevel: paint.setStrokeJoin(Paint.Join(.BEVEL)) - } - - let dash = internalState.lineDash - - if dash.lengths.isEmpty == false { - _ = paint.setPathEffect(DashPathEffect(dash.lengths.map { Float($0) }, Float(dash.phase))) - } - - return paint - } - - /// Strokes the current device-space path with the pen transformed by the CTM, - /// reproducing Cairo's stroke semantics (including non-uniform scales). - private func strokeUnderTransform(paint: Paint, canvas: AndroidGraphics.Canvas) { - - let ctm = internalState.ctm - - // transform the device path back into user space - let userPath = AndroidGraphics.Path() - devicePath.transform(ctm.inverse.toAndroid(), userPath) - - _ = canvas.save() - canvas.concat(ctm.toAndroid()) - canvas.drawPath(userPath, paint) - canvas.restore() - } - - /// Draws the shadow pass: the shape silhouette in the shadow color at the - /// shadow offset (no blur, matching the Cairo backend's emulation). - private func drawShadow(_ shadow: (offset: CGSize, radius: CGFloat, color: CGColor), - _ draw: (AndroidGraphics.Canvas, Paint) -> ()) { - - let ctm = internalState.ctm - - // the offset is specified in user space - let deviceOffset = CGSize(width: ctm.a * shadow.offset.width + ctm.c * shadow.offset.height, - height: ctm.b * shadow.offset.width + ctm.d * shadow.offset.height) - - let paint = Paint() - paint.setAntiAlias(internalState.shouldAntialias) - paint.setStyle(Paint.Style(.FILL)) - paint.setColor(colorValue(shadow.color)) - - _ = canvas.save() - canvas.translate(Float(deviceOffset.width), Float(deviceOffset.height)) - draw(canvas, paint) - canvas.restore() - } - - private func colorValue(_ color: CGColor) -> Int32 { - - func component(_ value: CGFloat) -> UInt32 { - return UInt32((max(0, min(1, value)) * 255).rounded()) - } - - let argb: UInt32 = (component(color.alpha) << 24) - | (component(color.red) << 16) - | (component(color.green) << 8) - | component(color.blue) - - return Int32(bitPattern: argb) - } -} - -// MARK: - State - -internal extension AndroidCanvasContext { - - fileprivate final class State { - - var next: State? - var ctm = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) - var alpha: CGFloat = 1.0 - var fill: CGColor? - var stroke: CGColor? - var shadow: (offset: CGSize, radius: CGFloat, color: CGColor)? - var font: CGFont? - var fontSize: CGFloat = 0.0 - var characterSpacing: CGFloat = 0.0 - var textMode = CGTextDrawingMode() - var shouldAntialias = true - var lineWidth: CGFloat = 1.0 - var lineCap = CGLineCap() - var lineJoin = CGLineJoin() - var miterLimit: CGFloat = 10.0 - var lineDash: (phase: CGFloat, lengths: [CGFloat]) = (0.0, []) - var tolerance: CGFloat = 0.1 - - init() { } - - var copy: State { - - let copy = State() - - copy.next = next - copy.ctm = ctm - copy.alpha = alpha - copy.fill = fill - copy.stroke = stroke - copy.shadow = shadow - copy.font = font - copy.fontSize = fontSize - copy.characterSpacing = characterSpacing - copy.textMode = textMode - copy.shouldAntialias = shouldAntialias - copy.lineWidth = lineWidth - copy.lineCap = lineCap - copy.lineJoin = lineJoin - copy.miterLimit = miterLimit - copy.lineDash = lineDash - copy.tolerance = tolerance - - return copy - } - } -} - -// MARK: - Geometry Helpers - -internal extension CGAffineTransform { - - /// The result of applying `self` first, then `other`. - func multiplied(by other: CGAffineTransform) -> CGAffineTransform { - - return CGAffineTransform( - a: a * other.a + b * other.c, - b: a * other.b + b * other.d, - c: c * other.a + d * other.c, - d: c * other.b + d * other.d, - tx: tx * other.a + ty * other.c + other.tx, - ty: tx * other.b + ty * other.d + other.ty - ) - } - - var inverse: CGAffineTransform { - - let determinant = a * d - b * c - - guard determinant != 0 - else { return self } - - return CGAffineTransform( - a: d / determinant, - b: -b / determinant, - c: -c / determinant, - d: a / determinant, - tx: (c * ty - d * tx) / determinant, - ty: (b * tx - a * ty) / determinant - ) - } - - func toAndroid() -> AndroidGraphics.Matrix { - - let matrix = AndroidGraphics.Matrix() - - matrix.setValues([ - Float(a), Float(c), Float(tx), - Float(b), Float(d), Float(ty), - 0, 0, 1 - ]) - - return matrix - } -} - -internal extension PathElement { - - func applying(_ transform: CGAffineTransform) -> PathElement { - - switch self { - - case let .moveToPoint(point): - return .moveToPoint(point.applying(transform)) - - case let .addLineToPoint(point): - return .addLineToPoint(point.applying(transform)) - - case let .addQuadCurveToPoint(control, destination): - return .addQuadCurveToPoint(control.applying(transform), destination.applying(transform)) - - case let .addCurveToPoint(control1, control2, destination): - return .addCurveToPoint(control1.applying(transform), control2.applying(transform), destination.applying(transform)) - - case .closeSubpath: - return .closeSubpath - } - } -} - -#endif // canImport(AndroidGraphics) diff --git a/Sources/AndroidSilica/AndroidCanvasRenderer.swift b/Sources/AndroidSilica/AndroidCanvasRenderer.swift new file mode 100644 index 0000000..f5d4e85 --- /dev/null +++ b/Sources/AndroidSilica/AndroidCanvasRenderer.swift @@ -0,0 +1,516 @@ +// +// AndroidCanvasRenderer.swift +// AndroidSilica +// +// Created by Alsey Coleman Miller on 7/13/26. +// Copyright © 2026 PureSwift. All rights reserved. +// + +#if canImport(AndroidGraphics) + +import AndroidGraphics +import SwiftJava +import JavaIO +import JavaLangIO +import Foundation +import Silica + +/// A renderer drawing with `android.graphics.Canvas`: into a PDF, a bitmap, +/// or a canvas a view's draw pass hands over. +/// +/// Android's canvas has its origin at the top left with y down, as Silica +/// does, and keeps the transform and the clip in its own save stack. The +/// colors, the stroke style, the alpha, the blend mode and the shadow are +/// kept here and applied to each paint. PDF pages are in points (1/72 inch). +/// +/// - Note: `finish()` is mandatory for a PDF: the document is only written to +/// disk then. JNI objects must be used from a thread attached to the JVM: +/// make, use and finish a renderer on one thread. +/// - Note: Glyphs need API 31 (`Canvas.drawGlyphs`). Shadows aren't blurred. +/// Blend modes `PorterDuff` lacks draw as normal: color dodge and burn, +/// soft and hard light, difference, exclusion, hue, saturation, color, +/// luminosity and plus darker. A transparency layer composites with its +/// alpha and blend mode, but casts no shadow. +public final class AndroidCanvasRenderer: Renderer { + + // MARK: - Properties + + public let size: Silica.Size + + /// Device pixels per point. + public let scale: Double + + /// The canvas drawn on (a new one on each PDF page). + public private(set) var canvas: AndroidGraphics.Canvas + + private let pdfDocument: PdfDocument? + + private let pdfURL: URL? + + private let bitmap: AndroidGraphics.Bitmap? + + private var page: PdfDocument.Page? + + private var pageNumber: Int32 = 0 + + private var isFinished = false + + private var state = State() + + /// Saved states, with the canvas save count to restore to. + private var stack: [(state: State, saveCount: Int32)] = [] + + // MARK: - Initialization + + /// A PDF at a file URL, `size` points a page. Call `finish()` to write it. + public init(pdf url: URL, size: Silica.Size) throws(SilicaError) { + let document = PdfDocument() + let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), 1).create() + guard let page = document.startPage(info), let canvas = page.getCanvas() + else { throw SilicaError.invalidContext } + self.pdfDocument = document + self.pdfURL = url + self.bitmap = nil + self.size = size + self.scale = 1 + self.page = page + self.canvas = canvas + self.pageNumber = 1 + AndroidBackend.registerIfNeeded() + } + + /// A bitmap `size` points across, `scale` pixels per point. + public init(bitmap size: Silica.Size, scale: Double = 1) throws(SilicaError) { + let width = Int32((size.width * scale).rounded(.up)) + let height = Int32((size.height * scale).rounded(.up)) + guard width > 0, height > 0, + let bitmapClass = try? JavaClass(), + let bitmap = bitmapClass.createBitmap(width, height, Bitmap.Config(.ARGB_8888)) + else { throw SilicaError.noMemory } + self.pdfDocument = nil + self.pdfURL = nil + self.bitmap = bitmap + self.size = size + self.scale = scale + self.canvas = Canvas(bitmap) + if scale != 1 { + canvas.scale(Float(scale), Float(scale)) + } + state.ctm = AffineTransform(scaleX: scale, y: scale) + AndroidBackend.registerIfNeeded() + } + + /// A canvas someone else made (e.g. the one `View.onDraw` hands over), + /// `size` points across, whose matrix maps points to its pixels. + public init(canvas: AndroidGraphics.Canvas, size: Silica.Size, scale: Double = 1) { + self.pdfDocument = nil + self.pdfURL = nil + self.bitmap = nil + self.size = size + self.scale = scale + self.canvas = canvas + state.ctm = AffineTransform(scaleX: scale, y: scale) + AndroidBackend.registerIfNeeded() + } + + // MARK: - Graphics State + + public func saveState() { + stack.append((state, canvas.save())) + } + + public func restoreState() { + guard let saved = stack.popLast() else { return } + canvas.restoreToCount(saved.saveCount) + state = saved.state + } + + public func concatenate(_ transform: Silica.AffineTransform) { + state.ctm = transform.concatenating(state.ctm) + canvas.concat(transform.toAndroid()) + } + + public func setAlpha(_ alpha: Double) { + state.alpha = alpha + } + + public func setBlendMode(_ mode: Silica.BlendMode) { + state.blendMode = mode + } + + public func setShouldAntialias(_ shouldAntialias: Bool) { + state.shouldAntialias = shouldAntialias + } + + public func setFillColor(_ color: Silica.Color) { + state.fillColor = color + } + + public func setStrokeColor(_ color: Silica.Color) { + state.strokeColor = color + } + + public func setStrokeStyle(_ style: StrokeStyle) { + state.strokeStyle = style + } + + public func setShadow(_ shadow: Shadow?) { + state.shadow = shadow + } + + // MARK: - Painting + + public func fill(_ path: Silica.Path, rule: FillRule) { + let androidPath = path.toAndroid(rule: rule) + withShadow { canvas, color in + canvas.drawPath(androidPath, paint(.fill, color: color ?? state.fillColor)) + } + } + + public func stroke(_ path: Silica.Path) { + let androidPath = path.toAndroid(rule: .winding) + withShadow { canvas, color in + canvas.drawPath(androidPath, paint(.stroke, color: color ?? state.strokeColor)) + } + } + + public func clip(to path: Silica.Path, rule: FillRule) { + _ = canvas.clipPath(path.toAndroid(rule: rule)) + } + + public func clear(_ rect: Silica.Rect) { + let count = canvas.save() + _ = canvas.clipRect(rect.toAndroid()) + canvas.drawColor(0, PorterDuff.Mode(.CLEAR)) + canvas.restoreToCount(count) + } + + public func draw(_ image: Silica.Image, in rect: Silica.Rect) { + guard let bitmap = image.toAndroidBitmap() else { return } + withShadow { canvas, color in + if let color { + // the shadow of an image is its rectangle + canvas.drawRect(rect.toAndroid(), paint(.fill, color: color)) + } else { + let imagePaint = paint(.fill, color: .black) + imagePaint.setFilterBitmap(true) + canvas.drawBitmap(bitmap, nil, rect.toAndroid(), imagePaint) + } + } + } + + public func drawLinearGradient(_ gradient: Gradient, start: Silica.Point, end: Silica.Point, options: GradientOptions) { + let dx = end.x - start.x, dy = end.y - start.y + let length = (dx * dx + dy * dy).squareRoot() + guard length > 0, gradient.stops.isEmpty == false else { return } + let shader = LinearGradient(Float(start.x), Float(start.y), Float(end.x), Float(end.y), + colors(of: gradient), gradient.stops.map { Float($0.location) }, + Shader.TileMode(.CLAMP)) + // an end that doesn't extend is cut off by the line through it, across the axis + let count = canvas.save() + if options != [.drawsBeforeStartLocation, .drawsAfterEndLocation] { + let far = 1e6 + let ux = dx / length, uy = dy / length + let from = options.contains(.drawsBeforeStartLocation) ? -far : 0 + let to = options.contains(.drawsAfterEndLocation) ? length + far : length + let band = AndroidGraphics.Path() + let corners = [(from, -far), (to, -far), (to, far), (from, far)] + for (index, corner) in corners.enumerated() { + let x = Float(start.x + ux * corner.0 - uy * corner.1) + let y = Float(start.y + uy * corner.0 + ux * corner.1) + if index == 0 { band.moveTo(x, y) } else { band.lineTo(x, y) } + } + band.close() + _ = canvas.clipPath(band) + } + let gradientPaint = paint(.fill, color: .black) + _ = gradientPaint.setShader(shader) + canvas.drawPaint(gradientPaint) + canvas.restoreToCount(count) + } + + /// Paints a radial gradient. Android's gradients have one center: two + /// circles with different centers draw around the end circle's. + public func drawRadialGradient(_ gradient: Gradient, startCenter: Silica.Point, startRadius: Double, + endCenter: Silica.Point, endRadius: Double, options: GradientOptions) { + guard endRadius > 0, endRadius > startRadius, startRadius >= 0, gradient.stops.isEmpty == false else { return } + // stops at radii from the start circle's to the end circle's + let positions = gradient.stops.map { Float((startRadius + $0.location * (endRadius - startRadius)) / endRadius) } + let shader = RadialGradient(Float(endCenter.x), Float(endCenter.y), Float(endRadius), + colors(of: gradient), positions, Shader.TileMode(.CLAMP)) + let count = canvas.save() + if options.contains(.drawsAfterEndLocation) == false { + let circle = AndroidGraphics.Path() + circle.addCircle(Float(endCenter.x), Float(endCenter.y), Float(endRadius), AndroidGraphics.Path.Direction(.CW)) + _ = canvas.clipPath(circle) + } + if options.contains(.drawsBeforeStartLocation) == false, startRadius > 0 { + let hole = AndroidGraphics.Path() + hole.setFillType(AndroidGraphics.Path.FillType(.EVEN_ODD)) + hole.addRect(-1e6, -1e6, 1e6, 1e6, AndroidGraphics.Path.Direction(.CW)) + hole.addCircle(Float(startCenter.x), Float(startCenter.y), Float(startRadius), AndroidGraphics.Path.Direction(.CW)) + _ = canvas.clipPath(hole) + } + let gradientPaint = paint(.fill, color: .black) + _ = gradientPaint.setShader(shader) + canvas.drawPaint(gradientPaint) + canvas.restoreToCount(count) + } + + public func beginTransparencyLayer(in rect: Silica.Rect?) { + let paint = Paint() + paint.setAlpha(Int32((min(max(state.alpha, 0), 1) * 255).rounded())) + if let mode = state.blendMode.toAndroid() { + _ = paint.setXfermode(PorterDuffXfermode(mode)) + } + let saveCount = canvas.saveLayer(rect?.toAndroid(), paint) + stack.append((state, saveCount)) + state.alpha = 1 + state.shadow = nil + state.blendMode = .normal + } + + public func endTransparencyLayer() { + restoreState() + } + + /// Draws glyphs with `Canvas.drawGlyphs` (API 31), each under the text + /// matrix's linear part at its baseline origin. + public func draw(_ glyphs: [Glyph], at positions: [Silica.Point], font: Silica.Font, + textMatrix: Silica.AffineTransform, mode: TextDrawingMode) { + guard let face = font.face as? AndroidFontHandle, font.size > 0, glyphs.isEmpty == false else { return } + let styles: [PaintStyle] + switch mode { + case .fill, .fillClip: styles = [.fill] + case .stroke, .strokeClip: styles = [.stroke] + case .fillStroke, .fillStrokeClip: styles = [.fill, .stroke] + case .invisible, .clip: return + } + let matrix = textMatrix.linear.toAndroid() + withShadow { canvas, shadowColor in + for style in styles { + let glyphPaint = paint(style, color: shadowColor ?? (style == .fill ? state.fillColor : state.strokeColor)) + glyphPaint.setTextSize(Float(font.size)) + for (glyph, position) in zip(glyphs, positions) { + guard let glyphFont = face.font(for: glyph) ?? face.baseFont else { continue } + let count = canvas.save() + canvas.translate(Float(position.x), Float(position.y)) + canvas.concat(matrix) + canvas.drawGlyphs([Int32(glyph)], 0, [0, 0], 0, 1, glyphFont, glyphPaint) + canvas.restoreToCount(count) + } + } + } + } + + // MARK: - Document + + public func beginPage() { + guard let document = pdfDocument, isFinished == false else { return } + if page != nil { + endPage() + } + pageNumber += 1 + let info = PdfDocument.PageInfo.Builder(Int32(size.width), Int32(size.height), pageNumber).create() + guard let newPage = document.startPage(info), let newCanvas = newPage.getCanvas() else { return } + page = newPage + canvas = newCanvas + // a page starts with no transform or clip + stack.removeAll() + state.ctm = .identity + } + + public func endPage() { + guard let document = pdfDocument, let openPage = page else { return } + document.finishPage(openPage) + page = nil + } + + /// Writes the PDF to disk and closes it. A PDF isn't written without it. + public func finish() throws(SilicaError) { + guard isFinished == false else { return } + defer { isFinished = true } + guard let document = pdfDocument, let url = pdfURL else { return } + if page != nil { + endPage() + } + do { + let stream = try FileOutputStream(url.path) + try document.writeTo(stream) + try stream.close() + } catch { + throw SilicaError.writeError + } + document.close() + } + + public func makeImage() -> Silica.Image? { + guard let bitmap else { return nil } + return Silica.Image(bitmap, scale: scale) + } +} + +// MARK: - Private + +private extension AndroidCanvasRenderer { + + struct State { + var ctm: Silica.AffineTransform = .identity + var fillColor: Silica.Color = .black + var strokeColor: Silica.Color = .black + var strokeStyle = StrokeStyle() + var alpha: Double = 1 + var blendMode: Silica.BlendMode = .normal + var shouldAntialias = true + var shadow: Shadow? + } + + enum PaintStyle { + case fill + case stroke + } + + /// A paint in a color with the alpha and blend mode; a stroke paint has the stroke style. + func paint(_ style: PaintStyle, color: Silica.Color) -> Paint { + let paint = Paint() + paint.setAntiAlias(state.shouldAntialias) + paint.setColor(color.opacity(state.alpha).androidValue) + if let mode = state.blendMode.toAndroid() { + _ = paint.setXfermode(PorterDuffXfermode(mode)) + } + switch style { + case .fill: + paint.setStyle(Paint.Style(.FILL)) + case .stroke: + let stroke = state.strokeStyle + paint.setStyle(Paint.Style(.STROKE)) + paint.setStrokeWidth(Float(stroke.lineWidth)) + paint.setStrokeMiter(Float(stroke.miterLimit)) + switch stroke.lineCap { + case .butt: paint.setStrokeCap(Paint.Cap(.BUTT)) + case .round: paint.setStrokeCap(Paint.Cap(.ROUND)) + case .square: paint.setStrokeCap(Paint.Cap(.SQUARE)) + } + switch stroke.lineJoin { + case .miter: paint.setStrokeJoin(Paint.Join(.MITER)) + case .round: paint.setStrokeJoin(Paint.Join(.ROUND)) + case .bevel: paint.setStrokeJoin(Paint.Join(.BEVEL)) + } + // Android needs an even number of lengths + var lengths = stroke.dash.map { Float($0) } + if lengths.count % 2 == 1 { lengths += lengths } + if lengths.isEmpty == false, lengths.allSatisfy({ $0 >= 0 }), lengths.contains(where: { $0 > 0 }) { + _ = paint.setPathEffect(DashPathEffect(lengths, Float(stroke.dashPhase))) + } + } + return paint + } + + /// Draws `body` twice when there's a shadow: first at the shadow's offset + /// in the shadow color (the silhouette, unblurred), then as itself, with nil. + func withShadow(_ body: (AndroidGraphics.Canvas, Silica.Color?) -> Void) { + if let shadow = state.shadow, shadow.color.alpha > 0, let inverse = state.ctm.invertedIfPossible() { + // the offset is in base space, `scale` pixels a point: the same move in user space + let offset = Silica.Size(width: shadow.offset.width * scale, height: shadow.offset.height * scale) + .applying(inverse.linear) + let count = canvas.save() + canvas.translate(Float(offset.width), Float(offset.height)) + body(canvas, shadow.color) + canvas.restoreToCount(count) + } + body(canvas, nil) + } + + /// The gradient's colors with the alpha. + func colors(of gradient: Gradient) -> [Int32] { + gradient.stops.map { $0.color.opacity(state.alpha).androidValue } + } +} + +// MARK: - Conversion + +internal extension Silica.Color { + + /// The color as Android's ARGB value. + var androidValue: Int32 { + func component(_ value: Double) -> UInt32 { + UInt32((max(0, min(1, value)) * 255).rounded()) + } + let argb = (component(alpha) << 24) | (component(red) << 16) | (component(green) << 8) | component(blue) + return Int32(bitPattern: argb) + } +} + +internal extension Silica.Rect { + + func toAndroid() -> RectF { + RectF(Float(minX), Float(minY), Float(maxX), Float(maxY)) + } +} + +internal extension Silica.AffineTransform { + + func toAndroid() -> AndroidGraphics.Matrix { + let matrix = AndroidGraphics.Matrix() + matrix.setValues([Float(a), Float(c), Float(tx), + Float(b), Float(d), Float(ty), + 0, 0, 1]) + return matrix + } +} + +internal extension Silica.Path { + + func toAndroid(rule: FillRule) -> AndroidGraphics.Path { + let path = AndroidGraphics.Path() + path.setFillType(AndroidGraphics.Path.FillType(rule == .evenOdd ? .EVEN_ODD : .WINDING)) + for element in elements { + switch element { + case let .move(point): + path.moveTo(Float(point.x), Float(point.y)) + case let .line(point): + path.lineTo(Float(point.x), Float(point.y)) + case let .quadCurve(point, control): + path.quadTo(Float(control.x), Float(control.y), Float(point.x), Float(point.y)) + case let .curve(point, control1, control2): + path.cubicTo(Float(control1.x), Float(control1.y), Float(control2.x), Float(control2.y), + Float(point.x), Float(point.y)) + case .closeSubpath: + path.close() + } + } + return path + } +} + +internal extension Silica.BlendMode { + + /// The Porter-Duff mode, or nil to draw normally (also for modes + /// `PorterDuff` lacks). + func toAndroid() -> PorterDuff.Mode? { + switch self { + case .normal: return nil + case .multiply: return PorterDuff.Mode(.MULTIPLY) + case .screen: return PorterDuff.Mode(.SCREEN) + case .overlay: return PorterDuff.Mode(.OVERLAY) + case .darken: return PorterDuff.Mode(.DARKEN) + case .lighten: return PorterDuff.Mode(.LIGHTEN) + case .clear: return PorterDuff.Mode(.CLEAR) + case .copy: return PorterDuff.Mode(.SRC) + case .sourceIn: return PorterDuff.Mode(.SRC_IN) + case .sourceOut: return PorterDuff.Mode(.SRC_OUT) + case .sourceAtop: return PorterDuff.Mode(.SRC_ATOP) + case .destinationOver: return PorterDuff.Mode(.DST_OVER) + case .destinationIn: return PorterDuff.Mode(.DST_IN) + case .destinationOut: return PorterDuff.Mode(.DST_OUT) + case .destinationAtop: return PorterDuff.Mode(.DST_ATOP) + case .xor: return PorterDuff.Mode(.XOR) + case .plusLighter: return PorterDuff.Mode(.ADD) + case .colorDodge, .colorBurn, .softLight, .hardLight, .difference, .exclusion, + .hue, .saturation, .color, .luminosity, .plusDarker: + return nil + } + } +} + +#endif // canImport(AndroidGraphics) From bc8e7df74db2ef3b0d3284a55944c082aff87eb9 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 5/7] Rendered the StyleKit drawings through GraphicsContext on Android --- .../AndroidStyleKitTests.swift | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift b/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift index b2182fd..74abb0c 100644 --- a/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift +++ b/Tests/AndroidSilicaTests/AndroidStyleKitTests.swift @@ -27,32 +27,32 @@ import SilicaTestSupport struct AndroidStyleKitTests { @Test func simpleShapes() throws { - let data = try render(TestStyleKit.drawSimpleShapes(), name: "android_simpleShapes", size: CGSize(width: 240, height: 120)) + let data = try render(name: "android_simpleShapes", size: Silica.Size(width: 240, height: 120)) { TestStyleKit.drawSimpleShapes(in: $0) } try expectPDF(data) } @Test func advancedShapes() throws { - let data = try render(TestStyleKit.drawAdvancedShapes(), name: "android_advancedShapes", size: CGSize(width: 240, height: 120)) + let data = try render(name: "android_advancedShapes", size: Silica.Size(width: 240, height: 120)) { TestStyleKit.drawAdvancedShapes(in: $0) } try expectPDF(data) } @Test func swiftLogo() throws { - let size = CGSize(width: 200, height: 200) - let data = try render(TestStyleKit.drawSwiftLogo(frame: CGRect(origin: .zero, size: size)), name: "android_SwiftLogo", size: size) + let size = Silica.Size(width: 200, height: 200) + let data = try render(name: "android_SwiftLogo", size: size) { TestStyleKit.drawSwiftLogo(in: $0, frame: Silica.Rect(origin: .zero, size: size)) } try expectPDF(data) } @Test func singleLineText() throws { - let data = try render(TestStyleKit.drawSingleLineText(), name: "android_singleLineText", size: CGSize(width: 240, height: 120)) + let data = try render(name: "android_singleLineText", size: Silica.Size(width: 240, height: 120)) { TestStyleKit.drawSingleLineText(in: $0) } try expectPDF(data) } @Test func bitmapContext() throws { AndroidBackend.register() - let context = try AndroidCanvasContext(bitmap: CGSize(width: 20, height: 20)) - context.fillColor = CGColor(red: 1, green: 0, blue: 0) - context.addRect(CGRect(x: 0, y: 0, width: 20, height: 20)) + let context = GraphicsContext(try AndroidCanvasRenderer(bitmap: Silica.Size(width: 20, height: 20))) + context.fillColor = Silica.Color(red: 1, green: 0, blue: 0) + context.addRect(Silica.Rect(x: 0, y: 0, width: 20, height: 20)) context.fillPath() let image = try #require(context.makeImage()) @@ -66,19 +66,15 @@ struct AndroidStyleKitTests { // MARK: - Utilities - private func render(_ drawingMethod: @autoclosure () -> (), name: String, size: CGSize) throws -> Data { + private func render(name: String, size: Size, _ drawing: (GraphicsContext) -> Void) throws -> Data { AndroidBackend.register() let path = try Self.outputDirectory() + "/" + name + ".pdf" - let context = try AndroidCanvasContext(pdf: URL(fileURLWithPath: path), size: size) + let context = GraphicsContext(try AndroidCanvasRenderer(pdf: URL(fileURLWithPath: path), size: size)) - UIGraphicsPushContext(context) - - drawingMethod() - - UIGraphicsPopContext() + drawing(context) try context.finish() From 6953e4d82f086a48c2bbea1206437de416414a0f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 6/7] Depended on Silica without its Cairo and web traits --- Package.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 6d583b0..701c7ae 100644 --- a/Package.swift +++ b/Package.swift @@ -110,7 +110,9 @@ var package = Package( ), .package( url: "https://github.com/PureSwift/Silica.git", - branch: "master" + branch: "master", + // only the Silica module: not its Cairo or web renderers' packages + traits: [] ), ], targets: [ From 1cd9bac85f0c2bfb6154d47a64a7f6ff9840bf8d Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 25 Nov 2026 13:59:52 -0500 Subject: [PATCH 7/7] Documented drawing with AndroidCanvasRenderer --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ca0d451..6365674 100644 --- a/README.md +++ b/README.md @@ -18,24 +18,25 @@ Then you can compile the app from the Android IDE. ## Drawing with Silica -`AndroidSilica` draws [Silica](https://github.com/PureSwift/Silica)'s drawing API on `android.graphics.Canvas`. It is a product of its own, and `AndroidKit` doesn't include it. +`AndroidSilica` draws [Silica](https://github.com/PureSwift/Silica)'s drawing API on `android.graphics.Canvas`, with `AndroidCanvasRenderer`. It is a product of its own, and `AndroidKit` doesn't include it. ```swift import AndroidSilica -let context = try AndroidCanvasContext(pdf: url, size: CGSize(width: 200, height: 200)) -// ... CoreGraphics style drawing code ... +let context = GraphicsContext(try AndroidCanvasRenderer(pdf: url, size: Silica.Size(width: 200, height: 200))) +context.fill(Silica.Path(ellipseIn: Silica.Rect(x: 20, y: 20, width: 160, height: 160)), with: .red) try context.finish() // writes the PDF ``` -`AndroidCanvasContext` also has `init(bitmap:)` for raster output, and `init(canvas:size:)` to draw into a canvas you already have, such as the one a view's draw pass hands you. +`AndroidCanvasRenderer` also has `init(bitmap:scale:)` for pixels, and `init(canvas:size:scale:)` to draw into a canvas you already have, such as the one a view's draw pass hands you. AndroidGraphics has its own `Path`, `Rect`, `Point`, `Color`, `Font` and `BlendMode`: in a file that imports both, write Silica's with the module name. - Requires **API 31+** at runtime for glyph rendering (`Canvas.drawGlyphs`, `TextRunShaper`). - `finish()` is **mandatory** for PDF contexts — the document is only written to disk when it is called. - JNI-backed objects must be used from a JVM-attached thread; create, use, and finish a context on the same thread. -- The linear (scale/rotation) components of the text matrix are not applied to glyph shapes. - Unknown font names fall back to the system typeface (Android provides no font-matching failure signal). - Shadows are drawn without blur (a silhouette at the shadow offset). +- Blend modes `PorterDuff` lacks draw as normal (color dodge and burn, soft and hard light, difference, exclusion, hue, saturation, color, luminosity, plus darker), and a transparency layer casts no shadow. +- Radial gradients have one center: two circles with different centers draw around the end circle's. ### See Also