gpt4 book ai didi

ios - 如何将圆形蒙版应用到 UIImageView

转载 作者:行者123 更新时间:2023-11-30 12:56:36 33 4
gpt4 key购买 nike

我在其他问题中读到,为了将圆形蒙版应用于 UIImageView,我应该这样做:

self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
self.imageView.clipsToBounds = true

但由于某种原因,当我这样做时,我的图像就被隐藏了。当我删除应用蒙版的代码时,图像显示完美,但应用蒙版后什么也没有出现。

我不知道这是否是因为 UIImageView 位于另一个 UIView 内,但我不明白为什么这不起作用。

这些是我用来处理图像的文件:

import UIKit

class ChatViewController: UIViewController {

var v: ChatOverview!

init () {
super.init(nibName: nil, bundle: nil)

self.title = "Chat"
self.tabBarItem.image = UIImage(named: "Chat")
self.tabBarItem.title = "Chats"
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override func viewDidLoad() {
super.viewDidLoad()

v = ChatOverview(
withName: "Mariano Rajoy",
andImage: UIImage(named: "Rajoy")!
)
self.view.addSubview(v)

NSLayoutConstraint.activate([
v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
v.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
v.widthAnchor.constraint(equalToConstant: 200),
v.heightAnchor.constraint(equalToConstant: 200)
])
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

self.v.applyCircleMask()
}

}

以及ChatOverview类的定义:

import UIKit

class ChatOverview: UIView {

var image: UIImage!
var imageView: UIImageView!

init (withName name: String, andImage image: UIImage) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))

self.image = image

self.isOpaque = false
self.translatesAutoresizingMaskIntoConstraints = false

self.imageView = UIImageView(image: self.image)
self.imageView.contentMode = .scaleAspectFit
self.imageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(imageView)

NSLayoutConstraint.activate([
self.imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
self.imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
self.imageView.widthAnchor.constraint(equalTo: self.widthAnchor),
self.imageView.heightAnchor.constraint(equalTo: self.heightAnchor)
])
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

func applyCircleMask () {
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2.0
self.imageView.clipsToBounds = true
}

}

最佳答案

不要使用 ClipsToBounds,而是使用:

self.imageView.layer.masksToBounds = true

关于ios - 如何将圆形蒙版应用到 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330787/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com