我正在尝试创建一个可以在NSView中拖动和旋转的对象,并且已经使用NSBezierPath成功地做到了这一点。我创建了多个对象,并将它们存储在一个类中,并使用NSBezierPath.transform(使用: AffineTransform)来修改路径,以响应拖动和旋转输入。
这一切都很好,但我现在想要向形状添加文本,似乎有一套不同的处理文本的规则。
我试过通过创建CTFrame来使用核心文本,但不知道如何移动或旋转它。
为什么文本的处理与NSBezierPath如此不同,有什么好的理由吗?
这就是AffineTransform和CGAffineTransform之间的区别。整个事情相当令人困惑,而且很难找到好的文档来解释其中的区别。
下面是创建和移动形状的代码,它似乎工作得很完美。我不知道如何移动文本,理想情况下不需要重新创建。有没有办法平移和旋转CTFrame?
var path: NSBezierPath
var location: NSPoint {
didSet {
// move()
}
}
var angle: CGFloat {
didSet {
let dx = angle - oldValue
rotate(dx)
}
}
func createPath(){
// Create a simple path with a rectangle
self.path = NSBezierPath(rect: NSRect(x: -1*width/2.0, y: -1*height/2.0, width: width, height: height))
let line = NSBezierPath()
line.move(to: NSPoint(x: width/2.0, y:0))
line.line(to: NSPoint(x: width/2.0+leader, y:0))
self.path.append(line)
// Label !!
let rect = NSRect(x: width/2.0, y: 0, width: leader, height: height/2.0)
let attrString = NSAttributedString(string: assortmentLabel, attributes: attributesForLeftText)
self.labelFrame = textFrame(attrString: attrString, rect: rect)
// ??? How to rotate the CTFrame - is this even possible
move()
rotate(angle)
}
func rotate(_ da: CGFloat){
// Move to origin
let loc = AffineTransform(translationByX: -location.x, byY: -location.y)
self.path.transform(using: loc)
let rotation = AffineTransform(rotationByDegrees: da)
self.path.transform(using: rotation)
// Move back
self.path.transform(using: AffineTransform(translationByX: location.x, byY: location.y))
}
func move(){
let loc = AffineTransform(translationByX: location.x, byY: location.y)
self.path.transform(using: loc)
}
func draw(){
guard let context = NSGraphicsContext.current?.cgContext else {
return
}
color.set()
path.stroke()
if isSelected {
path.fill()
}
if let frame = self.labelFrame {
CTFrameDraw(frame, context)
}
}
// -----------------------------------
// Modify the item location
// -----------------------------------
func offsetLocationBy(x: CGFloat, y:CGFloat)
{
location.x=location.x+x
location.y=location.y+y
let loc = AffineTransform(translationByX: x, byY: y)
self.path.transform(using: loc)
}编辑:
我已经做了一些修改,现在在原点0,0处绘制形状,然后在绘制形状之前将转换应用到CGContext。这就完成了工作,使用CTDrawFrame现在可以正常工作了……
差不多吧..。
在我的测试应用程序上,它工作得很好,但当我将完全相同的代码集成到生产应用程序中时,文本显示颠倒了,所有字符都显示在彼此的顶部。
据我所知,绘制的视图并没有什么不同--使用了相同的NSView子类。
有没有其他东西可能会扰乱文本的绘制-似乎是isFlipped的问题,但为什么这种情况会发生在一个应用程序中,而不是另一个应用程序中。
其他的一切似乎都是正确的。把我的头发都扯出来了。
发布于 2018-08-15 08:10:02
经过一番努力,我似乎很幸运,测试应用程序可以正常工作,我需要在两个应用程序上设置textMatrix,以确保它在所有条件下都能正常工作。
似乎也不能创建CTFrame,然后缩放它并重新绘制它-好吧,这对我来说不起作用,所以我每次都必须在draw()方法中重新创建它!
https://stackoverflow.com/questions/51814664
复制相似问题