Swift - 图像控件(UIImageView)的用法
1,使用图像控件显示图片
let imageView = UIImageView(image:UIImage(named:"image1"))
imageView.frame = CGRect(x:10, y:30, width:300, height:150)
self.view.addSubview(imageView)
2,改变图片
imageView.image = UIImage(named:"icon2")
3,从文件目录中获取图片
let path = Bundle.main.path(forResource: "ball", ofType: "png")
let newImage = UIImage(contentsOfFile: path!)
let imageView = UIImageView(image:newImage)
self.view.addSubview(imageView)
4,从网络地址获取图片
//定义URL对象
let url = URL(string: "网络图片的URL地址")
//从网络获取数据流
let data = try! Data(contentsOf: url!)
//通过数据流初始化图片
let newImage = UIImage(data: data)
let imageView = UIImageView(image:newImage);
self.view.addSubview(imageView)
5,使用图像控件实现动画播放
UIImageView 中提供了存储多张图片来创建动画的功能,具体做法是,在 animationImages 属性中设置一个图片数组,然后使用 startAnimating 方法开始动画,最后用 stopAnimating 方法停止动画。同时,使用 animationDuration 属性中可以设置动画每帧切换的速度(秒)。
import UIKit
class ViewController: UIViewController {
var imageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView()
imageView.frame=CGRect(x:20, y:20, width:100, height:100)
//设置动画图片
imageView.animationImages = [UIImage(named:"icon1")!,UIImage(named:"icon2")!]
//设置每隔0.5秒变化一次
imageView.animationDuration=0.5
imageView.startAnimating()
self.view.addSubview(imageView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
imageView.startAnimating()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
imageView.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
6,保持图片比例
默认 UIImageView 会拉伸图片使其占满整个 UIImageView,如果不想让图片变形,可以将 ContentMode 设置为 Aspect Fit。
Swift - 图像控件(UIImageView)的用法imageView.contentMode = .scaleAspectFit
contentMode可设置:
case scaleToFill
case scaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
case scaleAspectFill // contents scaled to fill with fixed aspect. some portion of content may be clipped.
case redraw // redraw on bounds change (calls -setNeedsDisplay)
case center // contents remain same size. positioned adjusted.
case top
case bottom
case left
case right
case topLeft
case topRight
case bottomLeft
case bottomRight