如何使半圆的边框适应其尺寸

mnemlml8  于 2022-10-04  发布在  Swift
关注(0)|答案(2)|浏览(168)

我正在制作一款需要使用半圆的应用程序。但我不能使它的边框与物体的真实大小相匹配。现在我正在修剪圆圈,但我真的不知道你是否真的裁剪了视图。

下面是我如何修剪圆圈的方法:

Circle()
   .trim(from: 0, to: 0.5)
   .fill(Color.blue)
   .background(Color.red)

我的背景是红色,比我的新物体大了两倍。

t0ybt7op

t0ybt7op1#

最好是自己制作符合ShapeHalfCircle,而不是试图将Circle拼凑成您需要的形状。让我们更进一步,使其符合InsettableShape,以防您想要使用它来描边。

import SwiftUI

struct HalfCircle: InsettableShape {
    var _inset: CGFloat = 0

    func inset(by amount: CGFloat) -> Self {
        var copy = self
        copy._inset += amount
        return copy
    }

    func path(in rect: CGRect) -> Path {
        var path = Path()

        // This is a half-circle centered at the origin with radius 1.
        path.addArc(
            center: .zero,
            radius: 1,
            startAngle: .zero,
            endAngle: .radians(.pi),
            clockwise: false
        )
        path.closeSubpath()

        // Since it's the bottom half of a circle, we only want
        // to inset the left, right, and bottom edges of rect.
        let rect = rect
            .insetBy(dx: _inset, dy: 0.5 * _inset)
            .offsetBy(dx: 0, dy: -(0.5 * _inset))

        // This transforms bounding box of the path to fill rect.
        let transform = CGAffineTransform.identity
            .translatedBy(x: rect.origin.x + 0.5 * rect.size.width, y: 0)
            .scaledBy(x: rect.width / 2, y: rect.height)

        return path.applying(transform)
    }
}

我们可以用它来画这个:

使用这个Playground:

import PlaygroundSupport

PlaygroundPage.current.setLiveView(HalfCircle()
    .inset(by: 20)
    .fill(.black)
    .background(.gray)
    .aspectRatio(2, contentMode: .fit)
    .frame(width: 200)
    .padding()
)
gpnt7bae

gpnt7bae2#

您可以使用GeometryReader以不同方式对其进行掩码:

GeometryReader { proxy in
    Circle()
        .fill(.blue)
        .offset(y: -proxy.size.height) // <- Shows bottom part
        .frame(height: proxy.size.width) // <- Makes the circle match frame
        .background(.red) // <- Just for testing
}
.aspectRatio(2, contentMode: .fit) // <- Makes the frame ration 2 : 1 (landscape rectangle)
.clipped() // <- Removes out of bound drawings

相关问题