gpt4 book ai didi

ios - 如何将图像添加到 UIImageView?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:30 25 4
gpt4 key购买 nike

我正在尝试将图像添加到 UIImageView,但在我添加图像之后 UIImageView 为 nil。这是我的代码:

    class ViewController: UIViewController {

@IBOutlet var myView: UIView!
@IBOutlet weak var testImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(CGSize(width: 500,height: 500))
var path = UIBezierPath()
path.lineWidth = 1.0
path.moveToPoint(CGPoint(x: 150, y: 150))
var x = 151
for ;x<300;x++
{
path.addLineToPoint(CGPoint(x: x, y: x))
path.moveToPoint(CGPoint(x: x, y: x))
}
path.stroke()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
testImg = UIImageView(image: img)
testImg.frame = CGRect(x: 0,y: 0,width: 500,height: 500)
myView.addSubview(testImg)
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

当我尝试为 UIImageView 设置框架时,出现此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

可能是我没有正确创建图像。

更新

testImg = UIImageView(image: img)

这行代码覆盖了UIImageViewIBOutlet,去掉就简单了testImg.image = img固定问题。

最佳答案

简单方法:将该图像拖放到 Xcode 上的文件 View /项目导航器中。

选择 ImageView - 然后属性检查 - 在图像下 - 选择要加载的图像的文件名。

尽可能享受拖放。

硬道:

if let filePath = Bundle.main.path(forResource: "imageName", ofType:     "jpg"), let image = UIImage(contentsOfFile: filePath) {    imageView.contentMode = .scaleAspectFit
imageView.image = image
}

关于ios - 如何将图像添加到 UIImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39614539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com