我的 UITableView 有一个自定义单元格。如果用户为项目单元格选择图片,将显示图片:
我正在使用绘画代码中的以下代码制作矩形:
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()
}
}
}
There are two problems:
First, if I use UIImageView in my storyboard I just can draw an image and I don't know if I can draw a rectangle with my code or not. However, I checked it doesn't work.
Second if I use UIView, I can draw a rectangle, but if I want to draw an image I should use
UIColor(patternImage: UIImage(named: "picName")!)
, but I can't change this image frame the way I did for image view. For example, make it circle as I've shown in the picture.The question is, can I use UIImageView and is there any way to make my rectangle in UIImageView Or can I use UIView and is there any way to set my custom image. I mean change image size and frame.
最佳答案
使用单个 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 swift 中的文本属性。
在你的模型上使用这个方法的另一个重要原因是你应该缓存这个方法的结果,这样你就不必每次都计算它。惰性初始化器模式非常适合这个。
lazy var imageForThisItem: [UIImage] = {
// code as above, using "self" rather than item
}()
关于ios - 使用 UIImageView 或 UIView 快速绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41737101/