UITableView-UITableViewCell.Style .subtitle-如何使UIImageView成为圆形? -迅捷5

问题描述 投票:3回答:2

我得到了带有默认单元格样式的UITableView。 (设置为.subtitle样式)我要使其UIImageView通函。

cell.imageView.layer.borderWidth = 1
cell.imageView.layer.masksToBounds = false
cell.imageView.layer.borderColor = UIColor.white.cgColor
cell.imageView.layer.cornerRadius = profileImageView.frame.size.width/2
cell.imageView.clipsToBounds = true

在这种情况下将无法使用!

ios swift uitableview uiimage cell
2个回答
4
投票

由于https://stackoverflow.com/a/50462058/10489699,我找到了正确的方法。

        let itemSize = CGSize.init(width: 50, height: 50)
        UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale)
        let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
        cell.imageView?.image!.draw(in: imageRect)
        cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        cell.imageView?.layer.cornerRadius = (itemSize.width) / 2
        cell.imageView?.clipsToBounds = true

不要尝试if let image = cell.imageView?.image! {...},我不知道为什么,但是它会击中UIImageView!


1
投票

您可以使用此代码

public extension UIView {
    func round() {
        let width = bounds.width < bounds.height ? bounds.width : bounds.height
        let mask = CAShapeLayer()
        mask.path = UIBezierPath(ovalIn: CGRect(x: bounds.midX - width / 2, y: bounds.midY - width / 2, width: width, height: width)).cgPath
        self.layer.mask = mask
    }
}

您可以这样使用:

profileImageView.round()
© www.soinside.com 2019 - 2024. All rights reserved.