1. 程式人生 > >[Swift通天遁地]八、媒體與動畫-(15)使用TextKit實現精美的圖文混排效果

[Swift通天遁地]八、媒體與動畫-(15)使用TextKit實現精美的圖文混排效果

resource ide wrong mas 圖文 tex pan 屬性 異常

本文將演示制作一款更加精美的圖文的圖文混排效果:將文字緊貼圖片邊緣的圖文混排效果。

往項目中導入一份文本文件。

在左側的項目導航區,打開視圖控制器的代碼文件【ViewController.swift】

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
8 9 //設置根視圖的背景顏色為橙色 10 self.view.backgroundColor = UIColor.orange 11 12 //初始化一個文本視圖 13 let textView = UITextView(frame: CGRect(x: 20, y: 40, width: 280, height: 500)) 14 //設置文本視圖的背景顏色為橙色 15 textView.backgroundColor = UIColor.orange 16 //
設置文本視圖的字體大小 17 textView.font = UIFont.systemFont(ofSize: 22) 18 //將文本視圖添加到根視圖 19 self.view.addSubview(textView) 20 21 //獲得文本視圖的文字存儲屬性 22 let textStorage = textView.textStorage 23 //創建一個字符串,表示文本文件在項目中的路徑。 24 let path = Bundle.main.url(forResource: "
word", withExtension: "txt") 25 26 //添加一個異常捕捉語句,用來加載文本文件。 27 do 28 { 29 //讀取文本件中的文字內容 30 let string = try String(contentsOf: path!) 31 //將加載的文字,賦予文本視圖的文字存儲屬性 32 textStorage.replaceCharacters(in: NSRange(location: 0,length: 0), with: string) 33 } 34 catch 35 { 36 print("Something went wrong :(") 37 } 38 39 //讀取項目中的一張圖片素材 40 let image = UIImage(named: "Tea") 41 //創建一個圖像視圖,顯示加載的圖片素材。 42 let imageView = UIImageView(image: image) 43 //初始化一個矩形區域,作為圖像視圖的顯示區域。 44 let rect = CGRect(x: 80, y: 80, width: 150, height: 150) 45 //設置圖像視圖的顯示區域 46 imageView.frame = rect 47 48 //設置圖像視圖的圓角半徑,將圖像視圖修改為一個圓形。 49 imageView.layer.cornerRadius = 75 50 //對圖像視圖進行裁切邊緣。 51 imageView.layer.masksToBounds = true 52 //給圖像視圖添加一個寬度為10的邊框。 53 imageView.layer.borderWidth = 10 54 //將圖像視圖添加到根視圖 55 self.view.addSubview(imageView) 56 57 //由於需要按照圖像的邊緣,對文本視圖中的文字進行排列, 58 //所以需要知道圖像視圖在文本視圖中的顯示區域。 59 //在此將圖像視圖的邊緣屬性,轉換成使用文本視圖中的坐標系統。 60 var frame = textView.convert(imageView.bounds, from: imageView) 61 //由於文本視圖中的文本容器,在默認情況下,並不是位於文本視圖的原點位置,所以需要減去這個偏移距離。 62 frame.origin.x -= textView.textContainerInset.left; 63 //接著減去另一個方向上的偏移距離。 64 frame.origin.y -= textView.textContainerInset.top; 65 66 //使用貝塞爾路徑類,將顯示區域轉換成一個基於矢量的路徑。 67 let path2 = UIBezierPath(ovalIn: frame) 68 //將橢圓路徑賦予文本視圖的排除路徑屬性, 69 //即在文本視圖中排除橢圓路徑所形成的區域, 70 //使文字僅在被排除的區域之外進行排列, 71 //從而實現文字沿圖像邊緣排列的效果。 72 textView.textContainer.exclusionPaths = [path2] 73 } 74 75 override func didReceiveMemoryWarning() { 76 super.didReceiveMemoryWarning() 77 // Dispose of any resources that can be recreated. 78 } 79 }

[Swift通天遁地]八、媒體與動畫-(15)使用TextKit實現精美的圖文混排效果