【问题标题】:SwiftUI - How to draw border around scaled to fit NSImageSwiftUI - 如何在缩放周围绘制边框以适合 NSImage
【发布时间】:2021-04-06 17:11:45
【问题描述】:

我有一个缩放到当前窗口宽度/高度的图像。我需要在图像周围画一个边框。我已经尝试了下面的代码,但是,它并没有在图像周围绘制精确的边框(请参见随附的屏幕截图)。我错过了什么?

import SwiftUI

struct RectangleView: View {
    var body: some View {
        GeometryReader { geo in
            ZStack {
                Image("front")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 400, height: geo.size.height)
                    .clipShape(
                        RoundedRectangle(cornerRadius: 30)
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 30)
                            .stroke(lineWidth: 10).foregroundColor(Color.green)
                    )
            }
            .padding()
            .position(x:geo.frame(in:.global).midX,y:geo.frame(in:.global).midY)
        }
    }
}

下面是我的视图控制器中的代码。

import Cocoa
import SwiftUI

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rectangleView = RectangleView()
        let contentView = NSHostingController(rootView: rectangleView)
        let rectView = contentView.view
        rectView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(rectView)

        NSLayoutConstraint.activate([
            rectView.leadingAnchor.constraint(equalTo: rectView.superview!.leadingAnchor),
            rectView.trailingAnchor.constraint(equalTo: rectView.superview!.trailingAnchor),
            rectView.topAnchor.constraint(equalTo: rectView.superview!.topAnchor),
            rectView.bottomAnchor.constraint(equalTo: rectView.superview!.bottomAnchor)
        ])
    }

}

【问题讨论】:

    标签: swift cocoa swiftui


    【解决方案1】:

    你已经为图片 .frame(width: 400, height: geo.size.height)提供了一个静态框架

    因此,您需要具体说明纵横比。 将.aspectRatio(contentMode: .fit) 更改为.aspectRatio(contentMode: .fill)

    【讨论】:

    • 使用 .fill 不是解决方案。我需要图像始终保持在给定宽度内的纵横比。
    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 2011-01-19
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多