How to soften edges of a Rectangle SwiftUI - swiftui

I'm currently running into a problem of "harsh" edges when I try to create a rounded rectangle using a gradient.
In this gradient you can see around the corners it gets especially dark, and I'm not sure how to fix this.
I'm guessing it's stemming from using an extension to create the gradient so that I can use it as the foreground color instead of the background, but I'm not sure what I would use instead to fix this problem.
var body: some View {
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 20)
.gradientForeground(colors: [Color("MainColor1"), Color("MainColor2")])
.frame(width: geometry.size.width * 0.9, height: 100, alignment: .center)
.padding(.leading, geometry.size.width * 0.05)
}
}
}
extension View {
public func gradientForeground(colors: [Color]) -> some View {
self.overlay(LinearGradient(gradient: .init(colors: colors),
startPoint: .topLeading,
endPoint: .bottomTrailing))
.mask(self)
}
}

Since you are working on Shape because you used RoundedRectangle, the right and correct way of coloring is fill, your issue is not connected to View to make an extension but it is about Shape.
extension Shape {
public func gradientForeground(colors: [Color]) -> some View {
self.fill(LinearGradient(gradient: .init(colors: colors), startPoint: .topLeading, endPoint: .bottomTrailing))
}
}
Use case:
struct ContentView: View {
var body: some View {
RoundedRectangle(cornerRadius: 50)
.gradientForeground(colors: [Color.red, Color.yellow])
.frame(width: 300, height: 300, alignment: Alignment.center)
}
}

Related

SwiftUI overlay deprecated alternatives

I'm trying to follow this calculator tutorial but am running into several issues. One of the issues is the use of the .overlay method. I'm assuming it doesn't work because it is deprecated, but I can't figure out how to get the recommeded way or get anything else to work to solve it, so am reaching out for options.
Xcode 12.4
Target: iOS 14.4
Here is the code in that section:
struct CalculatorButtonStyle: ButtonStyle {
var size: CGFloat
var backgroundColor: Color
var foregroundColor: Color
var isWide: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 32, weight: .medium))
.frame(width: size, height: size)
.frame(maxWidth: isWide ? .infinity : size, alignment: .leading)
.background(backgroundColor)
.foregroundColor(foregroundColor)
/* //Commented out to compile
.overlay( {
if configuration.isPressed {
Color(white: 1.0, opacity: 0.2)
}
)
}
*/
//.clipShape(Capsule()) //this makes circle buttons
} //func
} //struct
I've tried commenting out that section which is the only way to have it compile, but then the button press action of showing a different color does not work.
Overlay is not deprecated. Where did you read that. I think your problem is that you try to use the overlay function in a button style, which is not possible. You can only use it in a view. The error you wrote behind it, also states that.
I'm also not sure what you want to achieve, because doesn't it work correct if you just not use the overlay?
I get this button without the overlay. Is that what you need?
With the button style:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Button("1") {
print("being pressed")
}
.buttonStyle(
CalculatorButtonStyle(
size: 40,
backgroundColor: .cyan,
foregroundColor: .black
)
)
}
.padding()
}
}
I also added the changed button style.
import SwiftUI
struct CalculatorButtonStyle: ButtonStyle {
var size: CGFloat
var backgroundColor: Color
var foregroundColor: Color
var isWide: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 32, weight: .medium))
.frame(width: size, height: size)
.frame(maxWidth: isWide ? .infinity : size, alignment: .leading)
.background(backgroundColor)
.foregroundColor(configuration.isPressed ? Color(white: 1.0, opacity: 0.2) : foregroundColor)
.clipShape(Capsule()) //this makes circle buttons
}
}
An overlay is not needed. Take advantage of the isPressed value of the configuration to change the color
struct CalculatorButtonStyle: ButtonStyle {
var size: CGFloat
var backgroundColor: Color
var foregroundColor: Color
var isWide: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 32, weight: .medium))
.frame(width: size, height: size)
.frame(maxWidth: isWide ? .infinity : size, alignment: .leading)
.background(backgroundColor)
.foregroundColor(configuration.isPressed
? Color(white: 1.0, opacity: 0.5)
: foregroundColor)
.clipShape(Capsule())
} //func
} //struct
You have two stray parentheses:
// Remove this
// ↓
.overlay( {
if configuration.isPressed {
Color(white: 1.0, opacity: 0.2)
}
) // ← Remove this
}
The stray left parenthesis (the one immediately after .overlay) prevents Swift from recognizing the trailing closure syntax and makes Swift think you are trying to use the deprecated version of overlay.
The stray right parenthesis is improperly nested relative to the right-brace on the following line.
If you copy and paste the code from the tutorial, or if you remove those two parentheses, the code compiles:
struct CalculatorButtonStyle: ButtonStyle {
var size: CGFloat
var backgroundColor: Color
var foregroundColor: Color
var isWide: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 32, weight: .medium))
.frame(width: size, height: size)
.frame(maxWidth: isWide ? .infinity : size, alignment: .leading)
.background(backgroundColor)
.foregroundColor(foregroundColor)
.overlay {
if configuration.isPressed {
Color(white: 1.0, opacity: 0.2)
}
}
.clipShape(Capsule())
}
}

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)

Align masked Rectangle in a ZStack while also changing masked area [SwiftUI]

For a rating display I am trying to split an Image up into two parts, a black and a red one and I would like the red part to take up a specific percentage of the whole image. The problem I am having is that the Rectangle is aligned to the centre of the other image and when changing the alignment of the ZStack to .leading, the Rectangle does move but unfortunately the masked area of the image does not change.
ZStack {
Image("Car")
Rectangle()
.foregroundColor(ColorManager.brand)
.frame(width: 20.0, height: 20.0)
.mask(Image("Car"))
}
Without alignment
ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
Image("Car")
Rectangle()
.foregroundColor(ColorManager.brand)
.frame(width: 20.0, height: 20.0)
.mask(Image("Car"))
}
With alignment
How could I change the alignment of the Rectangle to .leading, while also masking the leading part of the image?
edit: Desired effect
You need just make clipping at needed location. Here is a complete demo of possible approach (on custom CarView as I don't have car image like your).
Prepared with Xcode 12.1 / iOS 14.1
struct CarView: View {
var body: some View {
Image(systemName: "car").resizable()
.frame(width: 200, height: 80)
}
}
struct MaskShape: Shape {
var alignment: HorizontalAlignment = .center
func path(in rect: CGRect) -> Path {
switch alignment {
case .leading:
return Rectangle().path(in: rect.divided(atDistance: rect.width / 3, from: .minXEdge).slice)
case .center:
return Rectangle().path(in: rect.insetBy(dx: rect.width / 3, dy: 0))
case .trailing:
return Rectangle().path(in: rect.divided(atDistance: rect.width / 3, from: .maxXEdge).slice)
default:
return Rectangle().path(in: rect)
}
}
}
struct TestCarMaskView: View {
var body: some View {
VStack {
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape())
)
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape(alignment: .leading))
)
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape(alignment: .trailing))
)
}
}
}
so your code could look like (of course sizes of mask you can tune for your needs)
Image("Car")
.overlay(
Rectangle()
.foregroundColor(ColorManager.brand)
.mask(Image("Car"))
.clipShape(MaskShape(alignment: .leading))
)

Ignore horizontal safe area with vertical ScrollView

I am trying to create a layout with multiple horizontal ScrollViews inside a vertical ScrollView, similar to the template picker in Apple's Pages app. I would like the content of the horizontal ScrollViews to be visible beyond the safe area. However I seem to be unable to get the content of the vertical ScrollView outside the horizontal safe insets. This is visible when iPhones with a notch are used in landscape orientation.
I have tried adding negative padding to the content of the vertical ScrollView. This kind of works, but creates issues when using the device in portrait mode.
Below example code shows the issue. I would expect the rectangles to be visible in beyond the safe area when scrolling horizontally, but they get clipped. How can I make them visible beyond the safe area?
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView(.vertical) {
ScrollView(.horizontal) {
HStack {
Rectangle()
.frame(width: 200, height: 300)
Rectangle()
.frame(width: 200, height: 300)
Rectangle()
.frame(width: 200, height: 300)
}
} .edgesIgnoringSafeArea(.horizontal)
} .edgesIgnoringSafeArea(.horizontal)
}
}
You can detect when the device's orientation changes and adapt your view:
struct ContentView: View {
#Environment(\.verticalSizeClass) var verticalSizeClass
var body: some View {
Group {
if verticalSizeClass == .compact {
content.edgesIgnoringSafeArea(.horizontal)
} else {
content
}
}
}
var content: some View {
ScrollView(.vertical) {
ScrollView(.horizontal) {
HStack {
Rectangle()
.frame(width: 200, height: 300)
Rectangle()
.frame(width: 200, height: 300)
Rectangle()
.frame(width: 200, height: 300)
}
}
}
.edgesIgnoringSafeArea(.horizontal)
}
}

How to create a see-through Rectangle in SwiftUI

I want to make an Image 100% transparent through a small rectangle and 50% transparent from all others. As if making a small hole to see-through the small rectangle. Here is my code...
struct ImageScope: View {
var body: some View {
ZStack {
Image("test_pic")
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
Rectangle()
.frame(width: 200, height: 150)
.foregroundColor(Color.orange.opacity(0.0))
.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3))
}
}
}
For easier understanding...
Here is working approach. It is used custom shape and even-odd fill style.
Tested with Xcode 11.4 / iOS 13.4
Below demo with more transparency contrast for better visibility.
struct Window: Shape {
let size: CGSize
func path(in rect: CGRect) -> Path {
var path = Rectangle().path(in: rect)
let origin = CGPoint(x: rect.midX - size.width / 2, y: rect.midY - size.height / 2)
path.addRect(CGRect(origin: origin, size: size))
return path
}
}
struct ImageScope: View {
var body: some View {
ZStack {
Image("test_pic")
Rectangle()
.foregroundColor(Color.black.opacity(0.5))
.mask(Window(size: CGSize(width: 200, height: 150)).fill(style: FillStyle(eoFill: true)))
RoundedRectangle(cornerRadius: 3).stroke(Color.white, lineWidth: 3)
.frame(width: 200, height: 150)
}
}
}
Using blendMode(.destinationOut) you don't have to draw custom shape and it is only one line of code. Sometimes adding .compositingGroup() modifier is neccessary.
ZStack {
Color.black.opacity(0.5)
Rectangle()
.frame(width: 200, height: 200)
.blendMode(.destinationOut) // << here
}
.compositingGroup()
For clarity, this solution is based on eja08's answer but fully flushed out using an image. The blend mode .destinationOut creates the cutout in the black rectangle. The nested ZStack places the image in the background without being impacted by the blend mode.
struct ImageScope: View {
var body: some View {
ZStack {
Image("test_pic")
ZStack {
Rectangle()
.foregroundColor(.black.opacity(0.5))
Rectangle()
.frame(width: 200, height: 150)
.blendMode(.destinationOut)
.overlay(RoundedRectangle(cornerRadius: 3).stroke(.white, lineWidth: 3))
}
.compositingGroup()
}
}
}
The result: