🪶

Xcode26でMETAL使いたいのだがないぞ?

に公開

どうやら設定が違うらしい?

最近、METALなるものに興味を持ちました。C言語のような文法でコードを書くやつ。
これが使えるようになると、色をつけたり画像に特殊効果をつけることができるようになる。

Xcode16.3あたりは、標準で使えるが、Xcode26あたりはどうやらプラグインなのか?追加する必要があるらしい。

https://developer.apple.com/jp/metal/tools/

手順はこのサイトに記載されているのをクラフトワークさんに教えてもらった👀
https://developer.apple.com/documentation/xcode/downloading-and-installing-additional-xcode-components

早速試してみよう

  1. Xcodeでプロジェクトを作り画像と同じ名前のディレクトリを作成する。

cmd + nを押す。

公式のソースコードを修正して使用する。
https://developer.apple.com/documentation/swiftui/view/layereffect(_:maxsampleoffset:isenabled:)

#include <metal_stdlib>
#include <SwiftUI/SwiftUI_METAL.h>

using namespace metal;

[[ stitchable ]] half4 name1(float2 position, half4 color) {
    half4 result = color.a == 0 ? half4(1,0,0,1) : color;
    
    return result;
}

[[ stitchable ]] float2 name2(float2 position) {
    return position;
}

[[ stitchable ]] half4 name3(float2 position,
SwiftUI::Layer layer) {
    return half4(0,0,1,1);
}

SwiftUIのコードでモジュールを読み込む。赤い色が出ればOK!

import SwiftUI

struct ContentView: View {

    var body: some View {
        VStack {
            Text("Hello MetalShaders")
                .font(.largeTitle)
                .colorEffect(ShaderLibrary.name1())
            Text("This text uses a custom shader effect.")
                .font(.title2)
                .distortionEffect(ShaderLibrary.name2(),
                             maxSampleOffset: .zero)
        }
    }
}

#Preview {
    ContentView()
}

最後に

やってみた感想ですが、まだわからないことが多く色つけるだけだと何の役に立つのって感じですが、METALは画像に波紋をつけたりと特殊効果をつけることができるようです。参考までに海外の動画のリンク貼っておきます。YouTubeで勉強するのも良さそうです。

https://www.youtube.com/watch?v=EgzWwgRpUuw
https://www.youtube.com/watch?v=yBdY0UKBIx0

Discussion