UIBarButtonItem自定义视图方面填充快速4

时间:2018-11-02 15:52:04

标签: ios swift xcode

我正在开发一个应用,该应用在主ViewController中的回合UIBarButtonItem中显示用户的个人资料图片,因此我正在使用带有cornerRadiusclipsToBounds的自定义按钮启用后,我将UIImage的宽度调整为NavigationBar高度的75%,以适应它,我还使用了button.imageView?.contentMode = .scaleAspectFill

当我使用正方形图像(宽度=高度)时,它可以完美工作,但是如果我使用纵向或横向图像,则好像BarButton使用的是.scaleAspectFit

我已经尝试首先创建一个平方的UIImage裁剪原始个人资料图片,而没有任何运气。

这是我的条形码按钮:

func setProfileButton() {
    let width = self.navigationController!.navigationBar.frame.size.height * 0.75

    if let image = ResizeImage(CFUser.current!.getProfileImage(), to: width) {
        let button = UIButton(type: .custom)
        button.setImage(image, for: .normal)
        button.imageView?.contentMode = .scaleAspectFill
        button.addTarget(self, action: #selector(goProfile), for: .touchUpInside)
        button.frame = CGRect(x: 0, y: 0, width: width, height: width)
        button.layer.cornerRadius = button.bounds.width / 2
        button.clipsToBounds = true

        let barButton = UIBarButtonItem(customView: button)

        self.navigationItem.rightBarButtonItem = barButton
    }
}

这是ResizeImage代码:

func ResizeImage(_ image: UIImage, to width: CGFloat) -> UIImage? {
    let size = image.size
    let ratio = width / image.size.width
    let height = image.size.height * ratio
    let targetSize = CGSize(width: width, height: height)

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio,height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
    }

    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

这是处理方形图像的应用程序

Here is the app working with squared image

这是一张肖像照片

And this is with a portrait image

感谢您的帮助! :)

PD:我正在使用Xcode 10和Swift 4

1 个答案:

答案 0 :(得分:0)

由于肖像图像的尺寸与正方形图像不同,因此请计算最小尺寸并相应地更改图像尺寸。

在下面替换方法ResizeImage(_ image: UIImage, to width: CGFloat) -> UIImage?

func ResizeImage(_ image: UIImage, to width: CGFloat) -> UIImage? {

    let ratio = width / image.size.width
    let height = image.size.height * ratio
    let dimension = min(width, height)
    let targetSize = CGSize(width: dimension, height: dimension)

    let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)

    UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

方形图片:

enter image description here

肖像:

enter image description here