How to make a border from a view in SwiftUI? - swiftui

I'd like to make a 2px border from a view, but the border only accepts a ShapeStyle. I'm trying to do something like:
let specialRadialGradient = GeometryReader { geometry in
RadialGradient(
gradient: Gradient(
stops: [
.init(color: Color("gradient1").opacity(0.5), location: 0),
.init(color: Color("gradient2").opacity(0.5), location: 1)
]
),
center: .init(x: 0.1432, y: 0.7254
startRadius: .zero,
endRadius: geometry.size.width * 0.75
)
.background(Color.brandPrimary)
}
Text("Abc")
.frame(maxWidth: .infinity)
.padding()
.border(specialRadialGradient, 2)
However, since the specialRadialGradient view is wrapped in a GeometryReader to handle the radial gradient properly in all ratio sizes, it doesn't compile. How can I cut out a 2px border out of specialRadialGradient and apply it to the background of the text?

Instead of border it can be done with composition of background and blending mode.
Here is a demo of possible approach. Tested with Xcode 14 / iOS 16
*(gradient colours just replicated for demo)
let borderWidth = 2.0
Text("Abc")
.frame(maxWidth: .infinity)
.padding()
.background(
specialRadialGradient
.overlay(Rectangle().padding(borderWidth) // << here !!
.blendMode(.destinationOut))
.compositingGroup() // << important !!
)
Test code on GitHub

Related

SwiftUI: How can I align a view to a background image

I have been trying to align a view to a background image, but I haven't been able to find a solution that works for all devices. I am targeting iPhones in landscape orientation.
In this example I want to make the red rectangle align with the iMac screen. This code gets pretty close, by using an offset. It looks good in the preview canvas, but doesn't align in the Simulator or on a device.
I tried using .position(x:y:), but that was even more messy.
I found that if I crop the background so the target region is exactly centered, then it is possible, but I really hope that's not the only solution.
struct GeometryView: View {
let backgroundImageSize = CGSize(width: 1500, height: 694)
let frameSize = CGSize(width: 535, height: 304)
var body: some View {
GeometryReader { geometry in
let widthScale = geometry.size.width / backgroundImageSize.width
let heightScale = geometry.size.height / backgroundImageSize.height
let scale = widthScale > heightScale ? widthScale : heightScale
let frame = CGSize(width: frameSize.width * scale,
height: frameSize.height * scale)
ZStack {
Rectangle()
.frame(width: frame.width, height: frame.height)
.foregroundColor(.red).opacity(0.5)
.offset(x: 5, y: -8)
}
.frame(width: geometry.size.width, height: geometry.size.height)
.background(
Image("imac-on-desk")
.resizable()
.scaledToFill()
.ignoresSafeArea())
}
}
}
background image
this would work, but only on an iPhone 12. If you use .scaledToFill on the image the different display aspect ratios of phones will lead to different offsets. You could at least crop the background image , so the white screen is exactly in the center of the image.
var body: some View {
GeometryReader { geometry in
ZStack {
Image("background")
.resizable()
.scaledToFill()
.ignoresSafeArea()
Rectangle()
.foregroundColor(.red).opacity(0.5)
.frame(width: geometry.size.width / 2.45,
height: geometry.size.height / 2.1)
.offset(x: -geometry.size.width * 0.025, y: 0)
}
}
}

SwiftUI squared image in a circle

I try to draw a squared Image inside of a Circle to get something like that (without blue square here. It is just to show image squared border):
This code makes squared image over all circle.
ZStack() {
Circle()
.fill(.orange)
Image(systemName: "trash")
.resizable()
.foregroundColor(.blue)
.background(.orange)
}
This code makes a small image on the circle or no circle at all:
ZStack() {
Circle()
.fill(.orange)
Image(systemName: "trash")
.foregroundColor(.blue)
.background(.orange)
}
I try to find a solution to have squared image inside the circle. It should not goes outside of it.
Maybe, I would also need a small margin between image and circle's border.
Is there a way to do that easily? Or I have to use math to get circle border or something like that?
Asperi just beat me to it, but this view will just take an icon name and a radius and return a squared icon perfectly in a circle:
struct ImageOnCircle: View {
let icon: String
let radius: CGFloat
var squareSide: CGFloat {
2.0.squareRoot() * radius
}
var body: some View {
ZStack {
Circle()
.fill(.orange)
.frame(width: radius * 2, height: radius * 2)
Image(systemName: icon)
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.frame(width: squareSide, height: squareSide)
.foregroundColor(.blue)
}
}
}
Use:
ImageOnCircle(icon: "trash", radius: 150)
Here is a demo of possible approach - use overlay + geometry reader to calculate internal rectangle where image is injected.
Tested with Xcode 13 / iOS 15 (blue rect is of Preview one for selected image)
Circle()
.fill(.orange)
.overlay(GeometryReader {
let side = sqrt($0.size.width * $0.size.width / 2)
VStack {
Rectangle().foregroundColor(.clear)
.frame(width: side, height: side)
.overlay(
Image(systemName: "trash")
.resizable()
.foregroundColor(.blue)
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(width: 100, height: 100)

Swiftui - Add blur linear gradient

I would like to add a white text on the top of an image.
My strategy will be to add a gradient that will be blurred at the text zone (please check the attached picture)
Anyone got an idea how to do this?
How's this?
For the blur effect, just use the .blur() modifier - no need for a separate image that's blurred.
struct ContentView: View {
let gradient = LinearGradient(
gradient: Gradient(stops: [
.init(color: .purple, location: 0),
.init(color: .clear, location: 0.4)
]),
startPoint: .bottom,
endPoint: .top
)
var body: some View {
Image("Background")
.resizable()
.aspectRatio(contentMode: .fit)
.overlay(
ZStack(alignment: .bottom) {
Image("Background")
.resizable()
.blur(radius: 20) /// blur the image
.padding(-20) /// expand the blur a bit to cover the edges
.clipped() /// prevent blur overflow
.mask(gradient) /// mask the blurred image using the gradient's alpha values
gradient /// also add the gradient as an overlay (this time, the purple will show up)
HStack {
Image("Icon") /// app icon
.resizable()
.frame(width: 64, height: 64)
VStack(alignment: .leading) {
Text("Classroom of the Elite")
.bold()
Text("Horikita best girl")
.opacity(0.75)
}
.frame(maxWidth: .infinity, alignment: .leading) /// allow text to expand horizontally
Button { } label: {
Text("GET")
.bold()
.padding(8)
.background(Color.gray)
.cornerRadius(16)
}
}
.foregroundColor(.white)
.padding(20)
}
)
}
}

CornerRadius issue with GeometryReader in SwiftUI

I have a small red Rec inside GeometryReader, if I use cornerRadius on GeometryReader it will going crop the Rec, which I do not want it. See the deference in photos:
struct ContentView: View {
var body: some View {
GeometryReader { _ in
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100, alignment: .center)
.position(x: 0, y: 0)
}
.background(Color.yellow)
.frame(width: 200, height: 300, alignment: .center)
.cornerRadius(10) // <<: Here try comment and uncomment it to see the result!
}
}
without cornerRadius:
with cornerRadius:
If you only want the yellow to have the corner radius and to not crop the red square, give the corner radius to only the background:
.background(
Color.yellow
.cornerRadius(10)
)
If you want the red square to have a corner radius as well but not be cropped, give it a corner radius as well:
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100, alignment: .center)
.cornerRadius(10)
.position(x: 0, y: 0)
Giving the GeometryReader itself a corner radius is not something that I would expect to have straightforward results, since the GeometryReader itself is not rendered per say (or at least rendered like we normally think of visual components), but as we can see from your example, it's basically treated like a container view -- giving it a corner radius ends up cropping out everything outside the bounds of it's content minus the corner radius.

SwiftUI: vertical align dynamic sized Rectangle with Spacer in SwiftUI

It seems there is a potential bug in SwiftUI. I am trying to put a rectangle with opacity 0.5 on top of an image.
When I try to fix the transparent rectangle on top, from 100px width, it goes down instead of sticking to the top.
Here is the code:
ZStack {
VStack {
Image("movistar")
.resizable(capInsets: EdgeInsets(), resizingMode: .stretch)
.scaledToFit()
.cornerRadius(8)
.padding(15)
.frame(minWidth: Global.SCREEN_WIDTH)
}
VStack {
HStack {
Rectangle()
.fill(Color(red: 0, green: 0, blue: 0, opacity: 0.5))
.frame(width: 110, height: Global.SCREEN_WIDTH / 4)
}
Spacer()
}
.scaledToFit()
.cornerRadius(8)
.padding(15)
.frame(width: Global.SCREEN_WIDTH, height: Global.SCREEN_WIDTH)
There is no bug here. If you add a .background to all of your layers, you will see that because of the way you set up the view (ie. Spacer, scaledToFit, etc.) the actual frames of the views are not necessarily the edges of the image. You also have not set the alignment of any of the Stacks or Frames.
There are many ways to do what you are trying to do, but I believe this is the simplest:
var body: some View {
Image("movistar")
.resizable(capInsets: EdgeInsets(), resizingMode: .stretch)
.scaledToFit()
.cornerRadius(8)
.frame(minWidth: UIScreen.main.bounds.width)
.overlay(
Rectangle()
.fill(Color(red: 0, green: 0, blue: 0, opacity: 0.5))
.frame(width: 110, height: UIScreen.main.bounds.width / 4)
, alignment: .top
)
}
Finally got into a solution: .scaleToFit() was messing with the VStack(). After deleting, it worked perfectly. I also got rid of the HStack().