Swift —UIImageView的使用

UIImageView 再常見不過的東西了。。。


//創(chuàng)建

//創(chuàng)建的時(shí)候直接設(shè)置圖片
let imageView = UIImageView(image:UIImage(named:"girl"))

//先創(chuàng)建出對(duì)象再設(shè)置圖片
let imageView1 = UIImageView()
imageView1.image = UIImage(named:"girl")

//圖片獲取

1、從文件目錄中獲取圖片
let path = Bundle.main.path(forResource:"girl", ofType: "png")
let newImage = UIImage(contentsOfFile: path!)


2、網(wǎng)絡(luò)地址獲取圖片
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

對(duì)于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中有設(shè)置多張圖片一塊展示的功能,類似于幻燈片的自動(dòng)播放。其實(shí)現(xiàn)過程如下:

//設(shè)置圖片數(shù)組
imageView1.animationImages = [UIImage(named:"2")!,UIImage(named:"3")!]

//所有圖片展示完一遍的總時(shí)長(zhǎng)
imageView1.animationDuration = 2

//開始
imageView1.startAnimating()

//結(jié)束
imageView1.stopAnimating()

//添加點(diǎn)擊事件
UIImageView和UILabel類似,其用戶交互默認(rèn)關(guān)閉,我們要給其添加點(diǎn)擊事件,需要打開其用戶交互。

imageView1.isUserInteractionEnabled = true

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

imageView1.addGestureRecognizer(tapGestureRecognizer)

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

//屬性設(shè)置

//邊框設(shè)置
imageView.layer.borderColor = UIColor.redColor().CGColor
imageView.layer.borderWidth = 2

//圓角的設(shè)置
imageView.layer.cornerRadius = 150
imageView.layer.masksToBounds = true

UIImageView繼承UIView,很多常見的屬性在此就不列舉。。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容