Swift 可以透過 Core Graphics 自繪背景紋理。以下以斜線背景為例,說明如何建立一個可調整線寬、間距、顏色與旋轉角度的自訂視圖。

建立 UIView 子類,在 drawRect 中取得目前繪圖上下文,先平移與旋轉,再以迴圈畫出等距線條。
建立 BackgroundLineView 實例,設定 frame、線寬、間距、顏色與旋轉角度,加入畫面即可。
let tmpView = BackgroundLineView(frame: CGRectMake(0, 0, 300, 300), lineWidth: 4, lineGap: 4, lineColor: UIColor.blackColor().colorWithAlphaComponent(0.045), rotate: CGFloat(M_PI_4))
tmpView.center = self.view.center
self.view.addSubview(tmpView)
這種做法適合背景紋理、裝飾線條或低透明度底紋,也能依需求替換成不同顏色與密度。