在 UIImageView 中用背景颜色填充 UIImage

问题描述 投票:0回答:1

基本上是尝试重新创建 iOS 设置应用程序中的小图标。我已经尝试了多种堆栈溢出技术,但没有任何效果。我设法在 UIImage 周围添加填充,但背景不会与填充一起填充,而只是填充在 uiimage 周围。

let image = UIImage(systemName: "arrow.down")!.withAlignmentRectInsets(UIEdgeInsets(top: -5, left: -5, bottom: -5, right: -5))
        let imageView = UIImageView(image: image)
        imageView.tintColor = .white
        imageView.layer.cornerRadius = 5
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = .systemPink
        imageView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(imageView)

 imageView.widthAnchor.constraint(equalToConstant: 30),
 imageView.heightAnchor.constraint(equalToConstant: 30),
swift uikit uiimageview uiimage
1个回答
0
投票

简单的解决方案是将图像视图放在另一个视图中。使用所需的背景颜色和圆角设置该视图。

let cfg = UIImage.SymbolConfiguration(scale: .medium)
let image = UIImage(systemName: "arrow.down", withConfiguration: cfg)
let iv = UIImageView(image: image)
iv.tintColor = .white
let icon = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
icon.backgroundColor = .systemPink
icon.layer.cornerRadius = 5
icon.addSubview(iv)
addSubview(icon)
iv.translatesAutoresizingMaskIntoConstraints = false
icon.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    iv.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
    iv.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
    icon.widthAnchor.constraint(equalToConstant: 30),
    icon.heightAnchor.constraint(equalToConstant: 30),
    // Add constraints to position icon as needed
])
© www.soinside.com 2019 - 2024. All rights reserved.