背景:我正在使用核心图形在UIImageView上绘制。我最终想在核心图形绘制的上面绘制文本字符串。
这个(hackingwithswift.com)方法是我用来将文本绘制到图像上,将我的imageView设置为该图像,然后用核心图形进行绘制。但是我希望文本覆盖核心图形绘制。
现在我已经转向了https://dev59.com/XmEi5IYBdhLWcg3wd8EF#35574171,但它仍然不允许我在我的绘图上面写字。
无法正常工作。绘制文本字符串会完全擦除该条。如果将该条绘制代码移至字符串绘制代码下方,则两者均可见,但当然该条会覆盖字符串。
现在我已经转向了https://dev59.com/XmEi5IYBdhLWcg3wd8EF#35574171,但它仍然不允许我在我的绘图上面写字。
class MapViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
func drawScale() {
// establish 6 points to draw a little bar with
let length = CGFloat(80.0)
let bottom = imageView.bounds.size.height - 15.0
let left = CGFloat(20.0)
let top = bottom - 20.0
let middle = top + 10.0
let right = left + length
let topLeft = CGPoint(x: left, y: top)
let topRight = CGPoint(x: right, y: top)
let bottomRight = CGPoint(x: right, y: bottom)
let bottomLeft = CGPoint(x: left, y: bottom)
let middleLeft = CGPoint(x: left, y: middle)
let middleRight = CGPoint(x: right, y: middle)
// draw the bar
drawLineFrom(fromPoint: topLeft, toPoint: bottomLeft, color: UIColor.red.cgColor, width: 1.0, alias: false)
drawLineFrom(fromPoint: topRight, toPoint: bottomRight, color: UIColor.red.cgColor, width: 1.0, alias: false)
drawLineFrom(fromPoint: middleLeft, toPoint: middleRight, color: UIColor.red.cgColor, width: 1.0, alias: false)
// draw a text string
UIGraphicsBeginImageContext(self.imageView.frame.size)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [
NSFontAttributeName: UIFont.systemFont(ofSize: 12),
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: UIColor.red]
let scaleString = "45 feet"
scaleString.draw(at: CGPoint(x: 0, y: 50), withAttributes: attrs)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
/* Stroke a line between two CGPoints. Color, width, anti-alias options. */
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint, color: CGColor, width: CGFloat, alias: Bool) {
// 1
UIGraphicsBeginImageContext(self.imageView.frame.size)
let context = UIGraphicsGetCurrentContext()!
context.setShouldAntialias(alias)
self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.imageView.frame.size.width, height: self.imageView.frame.size.height))
// 2
context.move(to: fromPoint)
context.addLine(to: toPoint)
// 3
context.setLineWidth(width)
context.setStrokeColor(color)
// 4
context.strokePath()
// 5
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
self.imageView.alpha = 1.0
UIGraphicsEndImageContext()
}
}
无法正常工作。绘制文本字符串会完全擦除该条。如果将该条绘制代码移至字符串绘制代码下方,则两者均可见,但当然该条会覆盖字符串。