1、UIImageView + UIImage Demo
import UIKit
class UIImageViewViewController: UIViewController {
var imageView = UIImageView()
var imageChangeView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.CreatUI() //创建imageView 本地 文件中 网络图片获取
self.ChangeImage()
}
func ChangeImage() {
imageChangeView.frame = CGRect(x: 100, y: 300, 200, height: 200)
imageChangeView.backgroundColor = UIColor.blue
//设置动画
imageChangeView.animationImages = [UIImage(named:"1.jpg")!,UIImage (named:"2.jpg")!,UIImage (named:"3.jpg")!,UIImage (named:"4.jpg")!]
//设置每间隔1秒 循环一次
imageChangeView.animationDuration = 4
//保持图片比例默认 UIImageView 会拉伸图片使其占满整个 UIImageView,如果不想让图片变形,可以将 ContentMode 设置为 ToFill充满iamgeview、 AspectFit imageView内原比例。 AspectFill显示原来比例,不足的imageview扩大
imageChangeView.contentMode = .scaleToFill
self.view.addSubview(imageChangeView)
imageChangeView.startAnimating()
}
func CreatUI() {
//imageview创建
imageView = UIImageView(image:UIImage(named:"1.jpg"))
imageView.frame = CGRect(x: 100, y: 100, 200, height: 200)
self.view.addSubview(imageView)
//修改图片
imageView.image = UIImage(named:"2.jpg")
//目录中获取图片
let path = Bundle.main.path(forResource:"3",ofType:"jpg")
imageView.image = UIImage(contentsOfFile:path!)
//网络下载图片
let url = URL(string: "http://hangge.com/blog/images/logo.png")
let data = try! Data (contentsOf:url!)//网上获取数据流
//通过水流初始化图片
let newImage = UIImage (data:data)
imageView.image = newImage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}