import UIKit
var imageView:UIImageView!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//创建ImageView
imageView = UIImageView(frame: CGRect(x: 150, y: 250, width: 100, height: 100))
//设置ImageView显示的图片
imageView.image = UIImage(named: "image")
//从文件目录中获取图片
let path = Bundle.main.path(forResource: "image", ofType: "png")//将图片拖至项目中,并输入其名称和图片格式
let fileimage = UIImage(contentsOfFile: path!)
imageView.image = fileimage
//从网络地址获取图片
let url = URL(string: "imageURL")//输入图片地址
//从网络中获取数据流
let data = try! Data(contentsOf: url!)
//通过数据流初始化图片
let urlImage = UIImage(data: data)
imageView.image = urlImage
//实现动画播放
let image1 = UIImage(named: "image1")
let image2 = UIImage(named: "image2")
imageView.animationImages = [image1!,image2!]
imageView.animationDuration = 0.1//设置图片变换间隔
//设置图片比例
imageView.contentMode = .scaleToFill//不保持原图比例,充满imageView
imageView.clipsToBounds = true//将超出的部分裁剪掉
/*
scaleAspecFit 保持图片比例已合适的大小填充imageView
scaleAspectFill//保持图片比例并填充满imageView
*/
//将UIImageViewj添加到视图
self.view.addSubview(imageView)
}
//view即将显示的监听
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
imageView.startAnimating()//开始播放
}
//view即将消失的监听
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
imageView.stopAnimating()//结束播放
}
}
网友评论