如何从macOS Swift的documents目录加载图像? [英] How to load an image from documents directory on macOS Swift?

查看:48
本文介绍了如何从macOS Swift的documents目录加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将图像加载到Image中.我正在制作与iOS稍有不同的MacOS应用.

I am struggling with loading an image to Image. I am making an MacOS app which is slightly different than for iOS.

我搜索了Internet,但是我只找到了几种在iOS中进行制作的答案.

I searched Internet however I found only several responses how to make it in iOS.

请检查代码:

import SwiftUI
struct ContentView: View {
    let myUrl = URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg")
    init() {
        //TODO Do something with the myUrl which is valid (not nil)
    }
    var body: some View {
        Image("turtlerock")
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
       //I need to put the param to Image what I want to load an image from myUrl

    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

推荐答案

首先点击您的应用定位>签名和功能并删除应用程序沙箱,如下图所示:

First click on your app target > signing & capabilities and remove the App Sandbox as shown in the following picture:

现在,您可以访问不在应用程序捆绑包中的文件.

Now you can access files that are not located inside your app bundle.

struct ContentView: View {
    let image = NSImage(contentsOf: URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg"))!
    var body: some View {
        Image(nsImage: image)
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
    }
}

这篇关于如何从macOS Swift的documents目录加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆