微信搜索superit|邀请体验:大数据, 数据管理、OLAP分析与可视化平台 | 赞助作者:赞助作者

Swift —UIImageView的使用

ui aide_941 29℃

//创建

//创建的时候直接设置图片
let imageView = UIImageView(image:UIImage(named:"girl"))

//先创建出对象再设置图片
let imageView1 = UIImageView()
imageView1.image = UIImage(named:"girl")

//图片获取

1、从文件目录中获取图片
let path = Bundle.main.path(forResource:"girl", ofType: "png")
let newImage = UIImage(contentsOfFile: path!)


2、网络地址获取图片
let url = URL(string:"http://image.cnpp.cn/upload/images/20160905/09380421552_400x300.jpg")
let data = try! Data(contentsOf: url!)
let smallImage = UIImage(data: data)
//imageView1.image = smallImage
let imageView1 = UIImageView(image:smallImage)

//图片显示填充样式

imageView1.contentMode = UIViewContentMode.scaleAspectFit

对于UIImageView的图片填充样式有多种:

/*
         public enum UIViewContentMode : Int {
         
         
         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
         }
 */

//分组图片轮展
UIImageView中有设置多张图片一块展示的功能,类似于幻灯片的自动播放。其实现过程如下:

//设置图片数组
imageView1.animationImages = [UIImage(named:"2")!,UIImage(named:"3")!]

//所有图片展示完一遍的总时长
imageView1.animationDuration = 2

//开始
imageView1.startAnimating()

//结束
imageView1.stopAnimating()

//添加点击事件
UIImageView和UILabel类似,其用户交互默认关闭,我们要给其添加点击事件,需要打开其用户交互。

imageView1.isUserInteractionEnabled = true

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ViewController.tapGestureRecognizer(sender:)))

imageView1.addGestureRecognizer(tapGestureRecognizer)

func tapGestureRecognizer(sender:UITapGestureRecognizer) {
    //code
}

//属性设置

//边框设置
imageView.layer.borderColor = UIColor.redColor().CGColor
imageView.layer.borderWidth = 2

//圆角的设置
imageView.layer.cornerRadius = 150
imageView.layer.masksToBounds = true

UIImageView继承UIView,很多常见的属性在此就不列举。。

作者:刘高见
链接:https://www.jianshu.com/p/10f32174fb2d
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

转载请注明:SuperIT » Swift —UIImageView的使用

喜欢 (0)or分享 (0)