How to apply inner shadow on stroke of a shape in SwiftUI? - swiftui

I would like to apply an inner shadow on the stroke of a shape. I have found an function that handles the inner shadow (can't use iOS 16 yet), but I'm having a hard time trying to apply this function to the stroke itself.
Here's what I got:
struct ContentView: View {
var body: some View {
VStack {
PolygonShape(sides: 7)
.stroke(Color.white, lineWidth: 10)
PolygonShape(sides: 7)
.innerShadow(color: .red, radius: 10)
}
.padding(32)
.background(Color.black.ignoresSafeArea())
}
}
extension Shape {
func innerShadow(color: Color, radius: Double) -> some View {
overlay(
stroke(color, lineWidth: radius)
.blur(radius: radius)
.mask(self)
)
}
}
struct PolygonShape: Shape {
let sides: Int
func path(in rect: CGRect) -> Path {
let c = CGPoint(x: rect.width/2.0, y: rect.height/2.0)
let r = Double(min(rect.width,rect.height)) / 2.0
var vertices:[CGPoint] = []
for i in 0...sides {
let angle = (2.0 * Double.pi * Double(i)/Double(sides))
let pt = CGPoint(x: r * cos(angle), y: r * sin(angle))
vertices.append(CGPoint(x: pt.x + c.x, y: pt.y + c.y))
}
var path = Path()
for (n, pt) in vertices.enumerated() {
n == 0 ? path.move(to: pt) : path.addLine(to: pt)
}
path.closeSubpath()
return path
}
}
struct StackedElementsView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This is what it looks like but not what I want:
What I would like to do is put the inner red shadow just on the white stroke itself, so the stroke has red shadow in it only not in the shape.
Something similar to this:
I tried applying the inner shadow on the color itself but since it is not a shape it did not compile: .stroke(Color.white.innerShadow(color: .red, radius: 2)
How can I apply the inner shadow on a stroke color?

This isn't the cleanest or most complete answer, but it's simple.
The following code, in your var body...
ZStack {
PolygonShape(sides: 7)
.stroke(Color.white, lineWidth: 10)
PolygonShape(sides: 7)
.stroke(Color.black, lineWidth: 10)
.scaleEffect(1.07)
.shadow(color: .red, radius: 3)
PolygonShape(sides: 7)
.scaleEffect(0.965)
.shadow(color: .red, radius: 3)
}
...produces this type of border:
There's a red line around the shape, though, which may or may not be an easy fix, depending on your situation. Just throwing this as a temporary answer :) Alternatively, if you can get the shape to be just the border (with no fill), you could use .mask and mask it to a gradient of your choice.

Although not perfect and probably will not handle many cases, an alternate way is drawing the stroke, then another stroke half the size within in it that's blurred:
extension Shape {
func stroke<Stroke: ShapeStyle>(
_ content: Stroke,
lineWidth: Double = 1,
innerShadow: (color: Color, radius: Double)
) -> some View {
stroke(content, lineWidth: lineWidth / 2)
.blur(radius: innerShadow.radius)
.background(stroke(innerShadow.color, lineWidth: lineWidth))
}
}
PolygonShape(sides: 7)
.stroke(Color.white, lineWidth: 10, innerShadow: (Color.red, 2))

Related

Shape resizing animation on orientation change

I have an issue with the shadow shape not being animated at the same time as the discs.
Here's the corresponding code. You can test this on an iPad by changing the orientation.
This is a direct consequence of the ContentView. Removing the GeometryReader and using a fixed frame fixes it.
import SwiftUI
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
ZStack {
PlanetView()
.frame(width: geometry.size.width * 0.25, height: geometry.size.width * 0.25)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct PlanetView: View {
var body: some View {
GeometryReader { geometry in
ZStack {
Circle()
.fill(.blue)
Circle()
.foregroundColor(.green)
.overlay(PlanetShadowView())
.frame(width: geometry.size.width * 0.8, height: geometry.size.width * 0.8)
}
}
}
}
struct PlanetShadowView: View {
var offsetRatio: CGFloat = 15/100.0
func control1(_ size: CGSize) -> CGPoint {
let xOffset = offsetRatio * size.width
let yOffset = offsetRatio * size.height
return .init(x: xOffset, y: size.height - yOffset)
}
func control2(_ size: CGSize) -> CGPoint {
let xOffset = offsetRatio * size.width
let yOffset = offsetRatio * size.height
return .init(x: size.width - xOffset, y: size.height - yOffset)
}
var body: some View {
GeometryReader { geometry in
Path { path in
path.move(to: CGPoint(x: 0, y: geometry.size.height / 2))
path.addCurve(to: CGPoint(x: geometry.size.width, y: geometry.size.height / 2),
control1: control1(geometry.size),
control2: control2(geometry.size))
path.addArc(center: CGPoint(x: geometry.size.width / 2, y: geometry.size.height / 2),
radius: geometry.size.width / 2,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 180),
clockwise: false)
path.closeSubpath()
}
.fill(Color.black.opacity(0.25))
.rotationEffect(.degrees(-30))
}
}
}
struct PlanetView_Previews: PreviewProvider {
static var previews: some View {
PlanetView()
}
}
A solution for this is to make planet shadow as a shape, so it would render in the same GeometryReader transformation context as everything else.
Tested with Xcode 13.4 / iOS 15.5
Circle()
.foregroundColor(.green)
.overlay(
PlanetShadow() // << here !!
.fill(Color.black.opacity(0.25))
.rotationEffect(.degrees(-30)))
.frame(width: geometry.size.width * 0.8, height: geometry.size.width * 0.8)
}
}
}
}
struct PlanetShadow: Shape { // << here !!
var offsetRatio: CGFloat = 15/100.0
func path(in rect: CGRect) -> Path {
// calc here ...
Test module on GitHub
Add .drawingGroup(). This should render the composition as a whole before displaying it.

Custom shape registers taps outside drawn path

I created a custom Arc shape in SwiftUI, but when I add an onTapGesture modifier to it, it registers taps outside the area I drew for the Arc (it registers taps anywhere within the rect used to draw the Arc). How can I make sure the taps only register within the drawn path of the Arc, not the entire rect?
Here's the Arc shape I drew:
struct Arc: Shape {
let angle: Angle
let thickness: CGFloat
let clockwise: Bool
func path(in rect: CGRect) -> Path {
var path = Path()
let innerArcEndPoint = CGPoint(x: rect.maxX - thickness, y: 0)
let innerArcStartPoint = CGPoint(
x: innerArcEndPoint.x * cos(CGFloat(angle.radians)),
y: innerArcEndPoint.x * sin(CGFloat(angle.radians)))
path.move(to: innerArcStartPoint)
path.addArc(center: rect.origin, radius: innerArcEndPoint.x, startAngle: angle, endAngle: Angle.zero, clockwise: !clockwise)
path.addLine(to: CGPoint(x: rect.maxX, y: 0))
path.addArc(center: rect.origin, radius: rect.maxX, startAngle: Angle.zero, endAngle: angle, clockwise: clockwise)
path.closeSubpath()
return path
}
}
Here's me using the Arc with an onTapGesture modifier:
struct TestTappingArc: View {
var body: some View {
Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false)
.foregroundColor(.blue) // The only area I want to be tappable
.background(Color.orange) // The area I DON'T want to be tappable (but currently is tappable)
.frame(width: 100, height: 100)
.onTapGesture {
print("hello")
}
}
}
And here's what it looks like on screen:
You need to use contentShape with same shape to restrict hit-testing area (because view is always rectangular), like
Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false)
.foregroundColor(.blue)
.contentShape(Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false))
.onTapGesture { // << here !!
print("hello")
}
.background(Color.orange)
.frame(width: 100, height: 100)
Thanks Asperi for that answer--that does fix the problem. However, I realized an even simpler solution is just to move the background to after the onTapGesture modifier, like this:
Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false)
.foregroundColor(.blue)
.frame(width: 100, height: 100)
.onTapGesture {
print("hello")
}
.background(Color.orange)

How to animate views in turn

I want to animate the arriving of views on the screen, in turn, one by one. Now my application draws circles and they arrive on the screen at the same time. But I would like it if the first circle will take its position and only after this the second circle will start its animation and etc. What solutions does this problem have?
import SwiftUI
struct ContentView: View {
var body: some View {
GenrealView()
}
}
struct GenrealView: View {
#State var hide = false
var body: some View {
giveViewForBody()
}
func giveViewForBody() -> some View {
ZStack {
drawCircles()
Button(action: {
self.hide.toggle()
}) {
Text(hide ? "Show circles" : "Hide circles")
}.padding(50)
}
}
func drawCircles(times: Int = 4) -> some View {
ForEach(0..<times) { _ in
Circle()
.fill(Color.green)
.frame(width: 100, height: 100)
.position(x: -100, y: -100)
.offset(x: CGFloat(hide ? 0 : 100 + Int.random(in: 100...300)),
y: CGFloat(hide ? 0 : 200 + Int.random(in: 50...600)))
.animation(.easeIn(duration: 2.0))
}
}
}
Add a .delay to each Circle() and make the delay larger for each successive one. Add index in to your ForEach loop and then make the delay .delay(2.0 * Double(index)):
func drawCircles(times: Int = 4) -> some View {
ForEach(0..<times) { index in
Circle()
.fill(Color.green)
.frame(width: 100, height: 100)
.position(x: -100, y: -100)
.offset(x: CGFloat(hide ? 0 : 100 + Int.random(in: 100...300)),
y: CGFloat(hide ? 0 : 200 + Int.random(in: 50...600)))
.animation(Animation.easeIn(duration: 2.0).delay(2.0 * Double(index)))
}
}

SwiftUI InsettableShape with .strokeBoarder

Can someone please explain why my self made "myRectangle" that I have conformed to InsettableShape doesn't work with .strokeBorder but the built in Rectangle() does?
Here is myRectangle code;
struct myRectangle: InsettableShape {
var insetAmount: CGFloat = 0
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX * 1.2, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.midX * 1.2, y: rect.midY * 0.6))
path.addLine(to: CGPoint(x: rect.midX * 0.8, y: rect.midY * 0.6))
path.addLine(to: CGPoint(x: rect.midX * 0.8, y: rect.maxY))
return path
}
func inset(by amount: CGFloat) -> some InsettableShape {
var rectangle = self
rectangle.insetAmount -= amount
return rectangle
}
}
then modifying it with the .strokeBorder;
struct ColorCyclingRectangle: View {
var amount = 0.0
var steps = 100
var body: some View {
ZStack {
ForEach(0..<steps) { value in
myRectangle()
.inset(by: CGFloat(value))
.strokeBorder(self.color(for: value, brightness: 1), lineWidth: 2)
}
}
.drawingGroup()
}
func color(for value: Int, brightness: Double) -> Color {
var targetHue = Double(value) / Double(self.steps) + self.amount
if targetHue > 1 {
targetHue -= 1
}
return Color(hue: targetHue, saturation: 1, brightness: brightness)
}
}
I am expecting the rainbow effect but just get a gradient line.
I have tried modifying my path to - insetAmount but I just get a weird shape and the rainbow border is straight, not square
Am I misunderstanding somthing or does this modifyer only work on the default shapes?
Though this is an older questions I will make an attempt to answer it in hopes the OP is still interested or that it may help others.
You can most definitely use the strokeBorder() modifier on custom types that conform to the InsettableShape protocol noting that it is your responsibility to write the code that insets - reduces size - of your custom shape accordingly.
The first item I noticed in your code is that you are hardcoding some values within your path(in rect: CGRect) method which is why your output is not a square. Two options for this are:
Add width and height variables to myRectangle and use them in your path(in rect: CGRect) to create the shape
Create the shape using the entire size of rect and utilize the .frame() modifier on the container where you are creating your custom shape or on the shape directly to control its dimensions.
I am not sure which is preferable, but I will use option 2 as it seems this is how the built-in shapes work - in relation to width and height at least - and it makes it easier to comprehend the insetting code as follows
struct myRectangle: InsettableShape {
var insetAmount: CGFloat = 0
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.minX + insetAmount, y: rect.maxY - insetAmount))
path.addLine(to: CGPoint(x: rect.maxX - insetAmount, y: rect.maxY - insetAmount))
path.addLine(to: CGPoint(x: rect.maxX - insetAmount, y: rect.minY + insetAmount))
path.addLine(to: CGPoint(x: rect.minX + insetAmount, y: rect.minY + insetAmount))
path.addLine(to: CGPoint(x: rect.minX + insetAmount, y: rect.maxY - insetAmount))
return path
}
func inset(by amount: CGFloat) -> some InsettableShape {
var rectangle = self
rectangle.insetAmount += amount
return rectangle
}
}
In the above you will note:
I removed the 1.2, 0.8 and 0.6 and instead utilized minX, maxX, minY and maxY to create the shape utilizing the entirety of rect size
To inset a rectangle you need to bring each of the edge points inwards by the inset amount taking account that SwiftUI measures coordinates from top-left, so you can say top-left would be (0,0)
I have used the insetAmount variable within the code in path(in rect: CGRect) that creates the path. For example path.move(to: CGPoint(x: rect.minX + insetAmount, y: rect.maxY - insetAmount)) is the bottom-left point. To inset this point you need to move the X to the right rect.minX + insetAmount and Y upwards rect.maxY - insetAmount - we are subtracting from Y to move upwards per my point 2.
In your ColorCyclingRectangle custom View I only added a .frame(width: 300, height: 300) modifier to the ZStack container that you are creating your custom shape in so that I can control its size.
struct ColorCyclingRectangle: View {
var amount = 0.0
var steps = 100
var body: some View {
ZStack {
ForEach(0..<steps) { value in
myRectangle()
.inset(by: CGFloat(value))
.strokeBorder(self.color(for: value, brightness: 1), lineWidth: 2)
}
}
.drawingGroup()
.frame(width: 300, height: 300)
}
func color(for value: Int, brightness: Double) -> Color {
var targetHue = Double(value) / Double(self.steps) + self.amount
if targetHue > 1 {
targetHue -= 1
}
return Color(hue: targetHue, saturation: 1, brightness: brightness)
}
}
With this I was able to get the rainbow effect.
Hopefully this resolves your issue.

Positioning View using anchor point

I have several dozen Texts that I would like to position such that their leading baseline (lastTextBaseline) is at a specific coordinate. position can only set the center. For example:
import SwiftUI
import PlaygroundSupport
struct Location: Identifiable {
let id = UUID()
let point: CGPoint
let angle: Double
let string: String
}
let locations = [
Location(point: CGPoint(x: 54.48386479999999, y: 296.4645408), angle: -0.6605166885682314, string: "Y"),
Location(point: CGPoint(x: 74.99159120000002, y: 281.6336352), angle: -0.589411952788817, string: "o"),
]
struct ContentView: View {
var body: some View {
ZStack {
ForEach(locations) { run in
Text(verbatim: run.string)
.font(.system(size: 48))
.border(Color.green)
.rotationEffect(.radians(run.angle))
.position(run.point)
Circle() // Added to show where `position` is
.frame(maxWidth: 5)
.foregroundColor(.red)
.position(run.point)
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
This locates the strings such that their center is at the desired point (marked as a red circle):
I would like to adjust this so that the leading baseline is at this red dot. In this example, a correct layout would move the glyphs up and to the right.
I have tried adding .topLeading alignment to the ZStack, and then using offset rather than position. This will let me align based on the top-leading corner, but that's not the corner I want to layout. For example:
ZStack(alignment: .topLeading) { // add alignment
Rectangle().foregroundColor(.clear) // to force ZStack to full size
ForEach(locations) { run in
Text(verbatim: run.string)
.font(.system(size: 48))
.border(Color.green)
.rotationEffect(.radians(run.angle), anchor: .topLeading) // rotate on top-leading
.offset(x: run.point.x, y: run.point.y)
}
}
I've also tried changing the "top" alignment guide for the Texts:
.alignmentGuide(.top) { d in d[.lastTextBaseline]}
This moves the red dots rather than the text, so I don't believe this is on the right path.
I am considering trying to adjust the locations themselves to take into account the size of the Text (which I can predict using Core Text), but I am hoping to avoid calculating a lot of extra bounding boxes.
So, as far as I can tell, alignment guides can't be used in this way – yet. Hopefully this will be coming soon, but in the meantime we can do a little padding and overlay trickery to get the desired effect.
Caveats
You will need to have some way of retrieving the font metrics – I'm using CTFont to initialise my Font instances and retrieving metrics that way.
As far as I can tell, Playgrounds aren't always representative of how a SwiftUI layout will be laid out on the device, and certain inconsistencies arise. One that I've identified is that the displayScale environment value (and the derived pixelLength value) is not set correctly by default in playgrounds and even previews. Therefore, you have to set this manually in these environments if you want a representative layout (FB7280058).
Overview
We're going to combine a number of SwiftUI features to get the outcome we want here. Specifically, transforms, overlays and the GeometryReader view.
First, we'll align the baseline of our glyph to the baseline of our view. If we have the font's metrics we can use the font's 'descent' to shift our glyph down a little so it sits flush with the baseline – we can use the padding view modifier to help us with this.
Next, we're going to overlay our glyph view with a duplicate view. Why? Because within an overlay we're able to grab the exact metrics of the view underneath. In fact, our overlay will be the only view the user sees, the original view will only be utilised for its metrics.
A couple of simple transforms will position our overlay where we want it, and we'll then hide the view that sits underneath to complete the effect.
Step 1: Set up
First, we're going to need some additional properties to help with our calculations. In a proper project you could organise this into a view modifier or similar, but for conciseness we'll add them to our existing view.
#Environment(\.pixelLength) var pixelLength: CGFloat
#Environment(\.displayScale) var displayScale: CGFloat
We'll also need a our font initialised as a CTFont so we can grab its metrics:
let baseFont: CTFont = {
let desc = CTFontDescriptorCreateWithNameAndSize("SFProDisplay-Medium" as CFString, 0)
return CTFontCreateWithFontDescriptor(desc, 48, nil)
}()
Then some calculations. This calculates some EdgeInsets for a text view that will have the effect of moving the text view's baseline to the bottom edge of the enclosing padding view:
var textPadding: EdgeInsets {
let baselineShift = (displayScale * baseFont.descent).rounded(.down) / displayScale
let baselineOffsetInsets = EdgeInsets(top: baselineShift, leading: 0, bottom: -baselineShift, trailing: 0)
return baselineOffsetInsets
}
We'll also add a couple of helper properties to CTFont:
extension CTFont {
var ascent: CGFloat { CTFontGetAscent(self) }
var descent: CGFloat { CTFontGetDescent(self) }
}
And finally we create a new helper function to generate our Text views that uses the CTFont we defined above:
private func glyphView(for text: String) -> some View {
Text(verbatim: text)
.font(Font(baseFont))
}
Step 2: Adopt our glyphView(_:) in our main body call
This step is simple and has us adopt the glyphView(_:) helper function we define above:
var body: some View {
ZStack {
ForEach(locations) { run in
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.position(run.point)
Circle() // Added to show where `position` is
.frame(maxWidth: 5)
.foregroundColor(.red)
.position(run.point)
}
}
}
This gets us here:
Step 3: Baseline shift
Next we shift the baseline of our text view so that it sits flush with the bottom of our enclosing padding view. This is just a case of adding a padding modifier to our new glyphView(_:)function that utilises the padding calculation we define above.
private func glyphView(for text: String) -> some View {
Text(verbatim: text)
.font(Font(baseFont))
.padding(textPadding) // Added padding modifier
}
Notice how the glyphs are now sitting flush with the bottom of their enclosing views.
Step 4: Add an overlay
We need to get the metrics of our glyph so that we are able to accurately place it. However, we can't get those metrics until we've laid out our view. One way around this is to duplicate our view and use one view as a source of metrics that is otherwise hidden, and then present a duplicate view that we position using the metrics we've gathered.
We can do this with the overlay modifier together with a GeometryReader view. And we'll also add a purple border and make our overlay text blue to differentiate it from the previous step.
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.overlay(GeometryReader { geometry in
self.glyphView(for: run.string)
.foregroundColor(.blue)
.border(Color.purple, width: self.pixelLength)
})
.position(run.point)
Step 5: Translate
Making use of the metrics we now have available for us to use, we can shift our overlay up and to the right so that the bottom left corner of the glyph view sits on our red positioning spot.
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.overlay(GeometryReader { geometry in
self.glyphView(for: run.string)
.foregroundColor(.blue)
.border(Color.purple, width: self.pixelLength)
.transformEffect(.init(translationX: geometry.size.width / 2, y: -geometry.size.height / 2))
})
.position(run.point)
Step 6: Rotate
Now we have our view in position we can finally rotate.
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.overlay(GeometryReader { geometry in
self.glyphView(for: run.string)
.foregroundColor(.blue)
.border(Color.purple, width: self.pixelLength)
.transformEffect(.init(translationX: geometry.size.width / 2, y: -geometry.size.height / 2))
.rotationEffect(.radians(run.angle))
})
.position(run.point)
Step 7: Hide our workings out
Last step is to hide our source view and set our overlay glyph to its proper colour:
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.hidden()
.overlay(GeometryReader { geometry in
self.glyphView(for: run.string)
.foregroundColor(.black)
.border(Color.purple, width: self.pixelLength)
.transformEffect(.init(translationX: geometry.size.width / 2, y: -geometry.size.height / 2))
.rotationEffect(.radians(run.angle))
})
.position(run.point)
The final code
//: A Cocoa based Playground to present user interface
import SwiftUI
import PlaygroundSupport
struct Location: Identifiable {
let id = UUID()
let point: CGPoint
let angle: Double
let string: String
}
let locations = [
Location(point: CGPoint(x: 54.48386479999999, y: 296.4645408), angle: -0.6605166885682314, string: "Y"),
Location(point: CGPoint(x: 74.99159120000002, y: 281.6336352), angle: -0.589411952788817, string: "o"),
]
struct ContentView: View {
#Environment(\.pixelLength) var pixelLength: CGFloat
#Environment(\.displayScale) var displayScale: CGFloat
let baseFont: CTFont = {
let desc = CTFontDescriptorCreateWithNameAndSize("SFProDisplay-Medium" as CFString, 0)
return CTFontCreateWithFontDescriptor(desc, 48, nil)
}()
var textPadding: EdgeInsets {
let baselineShift = (displayScale * baseFont.descent).rounded(.down) / displayScale
let baselineOffsetInsets = EdgeInsets(top: baselineShift, leading: 0, bottom: -baselineShift, trailing: 0)
return baselineOffsetInsets
}
var body: some View {
ZStack {
ForEach(locations) { run in
self.glyphView(for: run.string)
.border(Color.green, width: self.pixelLength)
.hidden()
.overlay(GeometryReader { geometry in
self.glyphView(for: run.string)
.foregroundColor(.black)
.border(Color.purple, width: self.pixelLength)
.transformEffect(.init(translationX: geometry.size.width / 2, y: -geometry.size.height / 2))
.rotationEffect(.radians(run.angle))
})
.position(run.point)
Circle() // Added to show where `position` is
.frame(maxWidth: 5)
.foregroundColor(.red)
.position(run.point)
}
}
}
private func glyphView(for text: String) -> some View {
Text(verbatim: text)
.font(Font(baseFont))
.padding(textPadding)
}
}
private extension CTFont {
var ascent: CGFloat { CTFontGetAscent(self) }
var descent: CGFloat { CTFontGetDescent(self) }
}
PlaygroundPage.current.setLiveView(
ContentView()
.environment(\.displayScale, NSScreen.main?.backingScaleFactor ?? 1.0)
.frame(width: 640, height: 480)
.background(Color.white)
)
And that's it. It's not perfect, but until SwiftUI gives us an API that allows us to use alignment anchors to anchor our transforms, it might get us by!
this code takes care of the font metrics, and position text as you asked
(If I properly understood your requirements :-))
import SwiftUI
import PlaygroundSupport
struct BaseLine: ViewModifier {
let alignment: HorizontalAlignment
#State private var ref = CGSize.zero
private var align: CGFloat {
switch alignment {
case .leading:
return 1
case .center:
return 0
case .trailing:
return -1
default:
return 0
}
}
func body(content: Content) -> some View {
ZStack {
Circle().frame(width: 0, height: 0, alignment: .center)
content.alignmentGuide(VerticalAlignment.center) { (d) -> CGFloat in
DispatchQueue.main.async {
self.ref.height = d[VerticalAlignment.center] - d[.lastTextBaseline]
self.ref.width = d.width / 2
}
return d[VerticalAlignment.center]
}
.offset(x: align * ref.width, y: ref.height)
}
}
}
struct ContentView: View {
var body: some View {
ZStack {
Cross(size: 20, color: Color.red).position(x: 200, y: 200)
Cross(size: 20, color: Color.red).position(x: 200, y: 250)
Cross(size: 20, color: Color.red).position(x: 200, y: 300)
Cross(size: 20, color: Color.red).position(x: 200, y: 350)
Text("WORLD").font(.title).border(Color.gray).modifier(BaseLine(alignment: .trailing))
.rotationEffect(.degrees(45))
.position(x: 200, y: 200)
Text("Y").font(.system(size: 150)).border(Color.gray).modifier(BaseLine(alignment: .center))
.rotationEffect(.degrees(45))
.position(x: 200, y: 250)
Text("Y").font(.system(size: 150)).border(Color.gray).modifier(BaseLine(alignment: .leading))
.rotationEffect(.degrees(45))
.position(x: 200, y: 350)
Text("WORLD").font(.title).border(Color.gray).modifier(BaseLine(alignment: .leading))
.rotationEffect(.degrees(225))
.position(x: 200, y: 300)
}
}
}
struct Cross: View {
let size: CGFloat
var color = Color.clear
var body: some View {
Path { p in
p.move(to: CGPoint(x: size / 2, y: 0))
p.addLine(to: CGPoint(x: size / 2, y: size))
p.move(to: CGPoint(x: 0, y: size / 2))
p.addLine(to: CGPoint(x: size, y: size / 2))
}
.stroke().foregroundColor(color)
.frame(width: size, height: size, alignment: .center)
}
}
PlaygroundPage.current.setLiveView(ContentView())
Updated: you could try the following variants
let font = UIFont.systemFont(ofSize: 48)
var body: some View {
ZStack {
ForEach(locations) { run in
Text(verbatim: run.string)
.font(Font(self.font))
.border(Color.green)
.offset(x: 0, y: -self.font.lineHeight / 2.0)
.rotationEffect(.radians(run.angle))
.position(run.point)
Circle() // Added to show where `position` is
.frame(maxWidth: 5)
.foregroundColor(.red)
.position(run.point)
}
}
}
there is also next interesting variant, use ascender instead of above lineHeight
.offset(x: 0, y: -self.font.ascender / 2.0)