Skip to content

Instantly share code, notes, and snippets.

@edenwaith
Last active March 22, 2024 17:53
Show Gist options
  • Save edenwaith/16b85fb66ad732fce8738d759e16a0fe to your computer and use it in GitHub Desktop.
Save edenwaith/16b85fb66ad732fce8738d759e16a0fe to your computer and use it in GitHub Desktop.
Example in SwiftUI to demonstrate creating an Image with rounded corners with different radii
//
// CustomRoundedImageView.swift
//
// Created by Chad Armstrong on 3/2/24.
// Example in SwiftUI to demonstrate creating an Image which is clipped with a custom shape and different corner radii
// An alternative to this method in SwiftUI is to clip a shape using a .rect with custom corner radii via RectangleCornerRadii
import SwiftUI
struct CustomRoundedRectShape: Shape {
func path(in rect: CGRect) -> Path {
let rectHeight = rect.height
let rectWidth = rect.width
let topLeftRadius = rectHeight / 2.0
let topRightRadius = 16.0
let path = Path { path in
// Starting point
path.move(to: CGPoint(x: topLeftRadius, y: 0.0))
// Top line
path.addLine(to: CGPoint(x: rectWidth-topRightRadius, y: 0.0))
// Top right corner with a radius of 16.0
path.addRelativeArc(center: CGPoint(x: rectWidth-topRightRadius, y: topRightRadius), radius: topRightRadius, startAngle: Angle(degrees: 270), delta: Angle(degrees: 90))
// Right line
path.addLine(to: CGPoint(x: rectWidth, y: rectHeight))
// Bottom line
path.addLine(to: CGPoint(x: 0.0, y: rectHeight))
// Left line
path.addLine(to: CGPoint(x: 0.0, y: rectHeight - topLeftRadius))
// Top left corner with a radius that is half the height of the image
path.addRelativeArc(center: CGPoint(x: topLeftRadius, y: rectHeight - topLeftRadius), radius: topLeftRadius, startAngle: Angle(degrees: 90), delta: Angle(degrees: 270))
}
return path
}
}
struct CustomRoundedImageView: View {
var body: some View {
Image("BRF002-small")
.clipShape(CustomRoundedRectShape())
Spacer()
}
}
#Preview {
CustomRoundedImageView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment