UIBarButtonItem - 背景图片,drawInRect和setBackgroundImage - Swift

时间:2014-08-21 17:35:05

标签: ios swift uiimage uibarbuttonitem

我正在尝试将UIBarButtonItem的背景图像设置为我在应用程序中的其他位置成功显示的图像,但是我得到一个奇怪的伸展,我似乎无法解决。 与此同时,我正试图将照片裁剪成一个圆圈。

这是我的代码:

        var profileView : UIView = self.profilePhoto.valueForKey("view") as UIView
        var profileImage = (user.valueForKey("profile_photo") as UIImage)
        var width = profileView.bounds.size.width
        var size = CGSize(width: width, height: width)

        UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
        UIBezierPath(roundedRect: profileView.bounds, cornerRadius: width / 2).addClip()
        profileImage.drawInRect(profileView.bounds)

        println("width: \(profileImage.size.width), height: \(profileImage.size.height)")
        // Show image without any cropping
        //self.profilePhoto.setBackgroundImage(profileImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
        self.profilePhoto.setBackgroundImage(UIGraphicsGetImageFromCurrentImageContext(), forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
        UIGraphicsEndImageContext()

Image with cropping

Stretched Image no cropping

1 个答案:

答案 0 :(得分:4)

试试这个

   self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIGraphicsGetImageFromCurrentImageContext(), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)