我正在尝试构建一个可能看起来像这个Inkscape模型的自定义控件:
我正在使用drawRect()
做事,但我需要为某些元素设置动画,所以我决定切换到CALayer
s的组合。我一直使用CGContextRef
函数绘制文本,但是对于每个角色切换到CATextLayer
,我似乎无法正确转换它们。
我的一般方法是为每个角色创建一个CATextLayer
。我想我可以使用每个图层的preferredFrameSize()
来获取角色的最终大小。然后我想我会在我的对照layoutSubviews()
方法中调整它们的位置和旋转。
“我尝试了什么?”我觉得我一直坐在旋转,蒙着眼睛,投掷飞镖。你说它,我试过了。
我可以通过以下方式确定每个角色的旋转角度:
let baseline = (self.ringBox.width * 3 / 8) // radius out to the baseline arc
let circumference = baseline * Tau
var advance = wordWidth.half.negated // wordWidth was summed from the width of each character earlier
let angle = 0.75.rotations
for each in self.autoCharacters {
let charSize = each.bounds.size
advance += charSize.width.half
let charRotation = (advance / circumference - 0.75).rotations + angle
...
}
我注意到layoutSubviews()
似乎被调用了两次。为什么?我注意到第二次,preferredFrameSize()
似乎更薄了。为什么?是因为我设置affineTransform
并且它有累积效应。我试图最初将图层的位置设置为父框的中心,并且边界为preferredFrameSize,希望将其置于中心。然后应用转换。尽管多次尝试,但我得到了奇怪的位置,以及奇怪的剪辑。
所以我只是在寻找一个简单/直接的方法,将CATextLayer
定位在距离视图中心的给定半径/角度。
答案 0 :(得分:0)
最后,我为所有人编写了一个单独的应用程序:
以及显示图层preferredFrameSize()
的一些调试信息。有了这个,能够操纵事物并看到效果,我实际上能够很简单地解决它。
为给定单词(键入CATextLayer
)中的每个字符创建一个[CATextLayer]
后,我使用以下方法来定位单词的字符:
// pass 1 to:
// - baseline each characters rotation
// - size it and center it
// - accumulate the length of the whole word
var wordWidth:CGFloat = 0.0
for letter in word {
// baseline the transform first, because preferredFrameSize() is affected by any latent rotation in the current transform
letter.setAffineTransform(CGAffineTransformIdentity)
// the preferredFrameSize will now be the un rotated size of the single character
let size = letter.preferredFrameSize()
// move the letter to the center of the view
letter.frame = CGRect(origin: center - size.half, size: size)
// accumulate the length of the word as the length of characters
wordWidth += size.width
}
let Tau = CGFloat(M_PI * 2)
// the length of the circle we want to be relative to
let circumference = radius * Tau
// back up the "advance" to half of the word width
var advance = wordWidth.half.negated
for letter in word {
// retrieve the character dimensions
let charSize = letter.bounds.size
// advance half of the character, so we're at its center
advance += charSize.width.half
// determine the angle to rotate off of the nominal (which is 270 degrees)
let charRotation = (advance / circumference * Tau - (Tau * 3 / 4)) + angle
// start with an identity transform now
var transform = CGAffineTransformIdentity
// rotate it. this will rotate about the center of the character
transform = transform.rotated(charRotation)
// translate outwards to the ring
transform = transform.translated(CGPoint(x: 0, y: radius.negated))
// apply the transform
letter.setAffineTransform(transform)
// move the advance the other half of this character
advance += charSize.width.half
}