winit icon indicating copy to clipboard operation
winit copied to clipboard

Add 'Metal' feature for iOS/macOS uses CAMetalLayer on UIView/NSView

Open rebecca-src opened this issue 5 months ago • 1 comments

Hello winit Team :smiley:,

thank you for this awesome repository :thumbsup:

I was experimenting with macOS/iOS and skia-safe with GPU Backend Metal. It was very difficult to get the Metal to work, especially on iOS because I needed the gl_or_metal_backed line 525 in platform_impl/ios/window.rs to be true, otherwise the render with window.request_redraw() will not work. With the metal feature enabeld the UIView/NSView will automatically create a CAMetalLayer as its layer.

The MetalLayer can then be extracted as followed:

use raw_window_handle::RawWindowHandle;

impl ApplicationHandler for Application {

    /* Cargo.toml
    winit = { version = "0.30.11", features = ["metal"] }
    metal = "0.32"
    objc = "0.2"
    raw-window-handle = "0.6"
    */

    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let window = event_loop.create_window(WindowAttributes::default()).expect("Failed to create window");
        let window_handle = window.window_handle().expect("Failed to retrieve a window handle");
        let view = match window_handle.as_raw() {
            RawWindowHandle::AppKit(appkit) => appkit.ns_view.as_ptr(),
            RawWindowHandle::UiKit(uikit) => uikit.ui_view.as_ptr(),
            _ => panic!("Wrong window handle type")
        } as *mut objc::runtime::Object;

        let metal_layer = unsafe {
            let metal_layer: *mut metal::CAMetalLayer = objc::msg_send![view, layer];
            let ml = metal::MetalLayer::from_ptr(metal_layer);
            ml
        }
    }
}

rebecca-src avatar Jun 14 '25 15:06 rebecca-src

I think that perhaps you might be looking for this crate: https://docs.rs/raw-window-metal/1.1.0/raw_window_metal/ .

tronical avatar Jun 18 '25 14:06 tronical