Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ var package = Package(
.library(
name: "AndroidNFC", targets: ["AndroidNFC"]
),
// Silica's drawing API on android.graphics.Canvas. Not part of AndroidKit,
// so AndroidKit doesn't bring Silica in.
.library(
name: "AndroidSilica", targets: ["AndroidSilica"]
),
],
dependencies: [
.package(
Expand All @@ -96,6 +101,10 @@ var package = Package(
url: "https://github.com/swift-android-sdk/swift-android-native.git",
branch: "main"
),
.package(
url: "https://github.com/PureSwift/Silica.git",
branch: "master"
),
],
targets: [
.target(
Expand Down Expand Up @@ -489,6 +498,57 @@ var package = Package(
sdkVersionDefine,
]
),
.target(
name: "AndroidSilica",
dependencies: [
.product(
name: "Silica",
package: "Silica"
),
"AndroidGraphics",
.product(
name: "SwiftJava",
package: "swift-java"
),
.product(
name: "JavaIO",
package: "swift-java"
),
.product(
name: "JavaLangIO",
package: "JavaLang"
),
],
swiftSettings: [
.swiftLanguageMode(.v6),
ndkVersionDefine,
sdkVersionDefine,
]
),
.testTarget(
name: "AndroidSilicaTests",
dependencies: [
"AndroidSilica",
"AndroidOS",
"AndroidApp",
"AndroidContent",
.product(
name: "SilicaTestSupport",
package: "Silica"
),
.product(
name: "AndroidContext",
package: "swift-android-native"
),
.product(
name: "SwiftJava",
package: "swift-java"
),
],
swiftSettings: [
.swiftLanguageMode(.v6),
]
),
],
swiftLanguageModes: [.v5, .v6]
)
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,27 @@ cd Demo

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.

```swift
import AndroidSilica

let context = try AndroidCanvasContext(pdf: url, size: CGSize(width: 200, height: 200))
// ... CoreGraphics style drawing code ...
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.

- 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).

### See Also

- [AndroidSwiftUI](https://github.com/PureSwift/AndroidSwiftUI) - SwiftUI for Android
Expand Down
164 changes: 164 additions & 0 deletions Sources/AndroidSilica/AndroidBackend.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
//
// AndroidBackend.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 rendering backend.
public enum AndroidBackend: SilicaBackendProtocol {

/// Registers Android as the default rendering backend.
public static func register() {

SilicaBackend.default = AndroidBackend.self
}

internal static func registerIfNeeded() {

guard SilicaBackend.default == nil else { return }
register()
}

// 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 decodePNG(_ data: Data) -> Silica.CGImage? {

let bytes = data.map { Int8(bitPattern: $0) }

guard let factoryClass = try? JavaClass<BitmapFactory>(),
let bitmap = factoryClass.decodeByteArray(bytes, 0, Int32(bytes.count))
else { return nil }

return Silica.CGImage(bitmap)
}

public static func encodePNG(_ image: Silica.CGImage) -> Data? {

guard let bitmap = image.toAndroidBitmap()
else { return nil }

let stream = ByteArrayOutputStream()

guard bitmap.compress(Bitmap.CompressFormat(.PNG), 100, stream)
else { return nil }

let bytes = stream.toByteArray()

return Data(bytes.map { UInt8(bitPattern: $0) })
}
}

// MARK: - CGImage Conversion

public extension Silica.CGImage {

/// Creates a Silica bitmap image from an Android bitmap,
/// normalizing the pixel format to premultiplied RGBA.
convenience init?(_ bitmap: AndroidGraphics.Bitmap) {

let width = Int(bitmap.getWidth())
let height = Int(bitmap.getHeight())

guard width > 0, height > 0
else { return nil }

let bytesPerRow = width * 4
var data = Data(count: bytesPerRow * height)

data.withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) in

let bytes = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self)

for y in 0 ..< height {

let row = bytes + (y * bytesPerRow)

for x in 0 ..< width {

// non-premultiplied ARGB color value
let color = UInt32(bitPattern: bitmap.getPixel(Int32(x), Int32(y)))

let alpha = UInt8((color >> 24) & 0xFF)
let red = UInt8((color >> 16) & 0xFF)
let green = UInt8((color >> 8) & 0xFF)
let blue = UInt8(color & 0xFF)

func premultiply(_ component: UInt8) -> UInt8 {
return UInt8((UInt16(component) * UInt16(alpha) + 127) / 255)
}

row[x * 4] = premultiply(red)
row[x * 4 + 1] = premultiply(green)
row[x * 4 + 2] = premultiply(blue)
row[x * 4 + 3] = alpha
}
}
}

self.init(width: width, height: height, bytesPerRow: bytesPerRow, data: data)
}

/// Converts to an Android bitmap (`ARGB_8888`).
func toAndroidBitmap() -> AndroidGraphics.Bitmap? {

var pixels = [Int32]()
pixels.reserveCapacity(width * height)

data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in

let bytes = buffer.baseAddress!.assumingMemoryBound(to: UInt8.self)

for y in 0 ..< height {

let row = bytes + (y * bytesPerRow)

for x in 0 ..< width {

let red = row[x * 4]
let green = row[x * 4 + 1]
let blue = row[x * 4 + 2]
let alpha = row[x * 4 + 3]

// un-premultiply into an ARGB color value
func unpremultiply(_ component: UInt8) -> UInt32 {
guard alpha > 0 else { return 0 }
return min(255, (UInt32(component) * 255 + UInt32(alpha) / 2) / UInt32(alpha))
}

let color: UInt32 = (UInt32(alpha) << 24)
| (unpremultiply(red) << 16)
| (unpremultiply(green) << 8)
| unpremultiply(blue)

pixels.append(Int32(bitPattern: color))
}
}
}

guard let bitmapClass = try? JavaClass<AndroidGraphics.Bitmap>()
else { return nil }

return bitmapClass.createBitmap(pixels, Int32(width), Int32(height), Bitmap.Config(.ARGB_8888))
}
}

#endif // canImport(AndroidGraphics)
Loading
Loading