4.5 C
New York
Thursday, December 12, 2024

ios – SwiftUI “masks” left and proper parts of a view


A RoundedRectangle as masks would appear like the obvious resolution:

Rectangle()
    .fill(.orange)
    .body(maxHeight: 70)
    .body(width: rectWidth)
    .masks {
        RoundedRectangle(cornerRadius: 5)
            .padding(.main, leftMaskWidth)
            .padding(.trailing, rightMaskWidth)
    }
    .background(.purple)

Nevertheless, you say this isn’t attainable, as a result of it would not work for hit testing. So listed here are two different attainable strategies.


1. Use .blendMode

The impact of a masks may also be achieved utilizing .blendMode. Particularly, mix mode .destinationOut can be utilized to “minimize out” a type from an underlying view. The “scope” of the mix mode must be constrained by making use of .compositingGroup, in any other case it goes on burning into decrease layers:

Rectangle()
    .fill(.orange)
    .body(maxHeight: 70)
    .body(width: rectWidth)
    .overlay {
        RoundedRectangle(cornerRadius: 5)
            .padding(.main, leftMaskWidth)
            .padding(.trailing, rightMaskWidth)
            .blendMode(.destinationOut)
            .background(.purple)
            .compositingGroup()
    }

Screenshot


2. Use a customized Form as clip form

An alternate method is to outline a customized Form, which might then be used as clip form:

struct CustomClipShape: Form {
    let leftMaskWidth: CGFloat
    let rightMaskWidth: CGFloat

    func path(in rect: CGRect) -> Path {
        Path(
            roundedRect: CGRect(
                x: rect.minX + leftMaskWidth,
                y: rect.minY,
                width: rect.width - leftMaskWidth - rightMaskWidth,
                top: rect.top
            ),
            cornerRadius: 5
        )
    }
}
Rectangle()
    .fill(.orange)
    .body(maxHeight: 70)
    .body(width: rectWidth)
    .clipShape(
        CustomClipShape(
            leftMaskWidth: leftMaskWidth,
            rightMaskWidth: rightMaskWidth
        )
    )
    .background(.purple)

The end result appears the identical as earlier than.


If neither of those strategies work to your hit testing both then maybe you’ll be able to elaborate extra on precisely what the difficulty is, in order that this may be addressed as the primary downside.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles