2017-01-19 27 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 
}()