TextureView is a Swift package that provides an efficient way to display Metal textures in iOS applications. It offers a customizable UIView subclass that can render Metal textures with various content modes and supports additional render commands.
- Display Metal textures in a UIView
- Support for different texture content modes (resize, aspect fill, aspect fit)
- Customizable pixel format
- Automatic drawable resizing
- Support for additional render commands
- Metal performance optimizations
- iOS 13.0+
- Swift 5.9+
Add the following to your Package.swift
file:
dependencies: [
.package(
url: "https://github.com/eugenebokhan/TextureView.git",
.upToNextMajor(from: "1.1.0")
)
]
- Import the module:
import TextureView
- Create a TextureView instance:
let device = MTLCreateSystemDefaultDevice()!
let textureView = try TextureView(device: device)
- Add the view to your view hierarchy:
view.addSubview(textureView)
- Set a texture to display:
textureView.texture = yourMTLTexture
You can change how the texture is displayed within the view:
textureView.textureContentMode = .aspectFit
Available modes are:
.resize
: Stretches or shrinks the texture to fill the view.aspectFill
: Scales the texture to fill the view while maintaining aspect ratio.aspectFit
: Scales the texture to fit within the view while maintaining aspect ratio
Change the pixel format of the view's drawable:
try textureView.setPixelFormat(.bgra8Unorm_srgb)
Enable or disable automatic resizing of the drawable when the view's bounds change:
textureView.autoResizeDrawable = false
To draw the texture, call the draw
method within your render loop:
let commandBuffer = commandQueue.makeCommandBuffer()!
textureView.draw(in: commandBuffer)
commandBuffer.commit()
You can also provide additional render commands:
textureView.draw(
additionalRenderCommands: { encoder in
// Your additional render commands here
},
in: commandBuffer
)
- The view uses
CAMetalLayer
for efficient rendering. - It supports the use of Metal fences for synchronization.
- The drawable is reused when possible to improve performance.
TextureView is licensed under MIT license.