2017-01-19 48 views
1

我有我的UITableView自定義單元格。如果用戶選擇一個項目單元的圖片會顯示一張圖片: enter image description here使用UIImageView或UIView進行快速繪製

如果不是,我將顯示項目名稱的前兩個字母: enter image description here

我用下面的繪製代碼代碼使長方形:

public class CircleStyleKit : NSObject { 

    //// Drawing Methods 

    public dynamic class func drawCanvas1(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 38, height: 38), resizing: ResizingBehavior = .aspectFit, circleLable: String = "DR", circleSize: CGSize = CGSize(width: 38, height: 38), textSize: CGFloat = 17) { 
     //// General Declarations 
     let context = UIGraphicsGetCurrentContext()! 

     //// Resize to Target Frame 
     context.saveGState() 
     let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 38, height: 38), target: targetFrame) 
     context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) 
     context.scaleBy(x: resizedFrame.width/38, y: resizedFrame.height/38) 
} // It's too long 

我顯示了部分代碼,因爲它太長了。

然後我用一個UIView繪製這個矩形:

import UIKit 

class CirclyStyleView: UIView { 

    override func draw(_ rect: CGRect) { 
     CircleStyleKit.drawCanvas1() 
     } 

    } 

} 

有兩個問題:

首先,如果我在故事板使用的UIImageView我只可以得出一個圖像 和我不知道是否可以用我的代碼繪製矩形。但是,我 檢查它不起作用。

其次,如果我使用UIView,我可以繪製一個矩形,但是如果我想繪製圖像,我應該使用UIColor(patternImage: UIImage(named: "picName")!),但我無法像改變圖像視圖一樣改變這個圖像幀。例如,讓它像我在圖片中顯示的那樣循環。

問題是,我可以使用UIImageView,並有任何方式來使我的矩形在UIImageView 或者我可以使用UIView,並有任何方式來設置我的自定義圖像。我的意思是改變圖像大小和框架。

回答

1

使用單一UIImageView和創造,鑑於它的情況下返回UIImage你的模型的方法。當必須繪製圖像時,繪製一個「圖像上下文」。

我不是一個迅速作家,所以在幾乎迅速...

func imageForThisItem(item : AnyObject) -> UIImage { 
    // not really "AnyObject", use the object type in your data source array 
    // even better, make this a method on that model object 

    if (/* item has an image, like the sailboat */) { 
     return UIImage(named:"SailboatImage") // or however you got the sailboat image 
    } else { 
     // initialize "size" to be the same size as the sailboat images 
     UIGraphicsBeginImageContextWithOptions(size, false, 0) 

     // do your circle and text drawing here within the rect (0,0,size.width,size.height) 
     UIColor.greenColor().setFill() 
     let bezier = UIBezierPath(rect : rect) 
     bezier.fill() 

     let initials = item.initials() // however you get this 
     // even better, if this is a model method, then self.initials() 

     let attributes = // an attribute dictionary, see link below 
     initials.drawInRect(rect, withAttributes: attributes) 
     // or use CGOffsetRect to provide a little margin 

     var image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image 
    } 
} 

文本Here's an example在迅速屬性。

在模型上使用此方法的另一個重要原因是您應該可能緩存此方法的結果,因此您不必每次都計算它。懶惰的初始化模式對此非常完美。

lazy var imageForThisItem: [UIImage] = { 
    // code as above, using "self" rather than item 
}()