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)
Related
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)
}
}
}
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)
}
)
}
}
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.
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))
)
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: