Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Last active August 26, 2022 17:04
Show Gist options
  • Save heestand-xyz/2ce84960a3c2c5f35e4b094e5ca18f1b to your computer and use it in GitHub Desktop.
Save heestand-xyz/2ce84960a3c2c5f35e4b094e5ca18f1b to your computer and use it in GitHub Desktop.
SwiftUI Path to Image Mask
import SwiftUI
import TextureMap
extension Path {
public func maskImage(size: CGSize) -> TMImage! {
guard let context = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: Int(size.width) * 4,
space: TMColorSpace.sRGB.cgColorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
else { return nil }
context.setFillColor(TMColor.black.cgColor)
context.addRect(CGRect(origin: .zero, size: size))
context.drawPath(using: .fill)
context.setFillColor(TMColor.white.cgColor)
context.addPath(cgPath)
context.drawPath(using: .fill)
guard let cgImage = context.makeImage()
else { return nil }
return TMImage(cgImage: cgImage, size: size)
}
}
@heestand-xyz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment