如何在swift 4中的自定义UIImagePickerController中设置一个按钮。

时间:2018-03-10 05:54:08

标签: ios swift uiimagepickercontroller

这是我的代码。我正在使用自定义imagepickercontroller处理图像操作,如裁剪,旋转,压缩和图像质量。我想为imagepickercontroller添加一个自定义按钮。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        let str=info[UIImagePickerControllerImageURL] as Any
        let name=(str as! URL).lastPathComponent
        imageName=name
        let fixOrientationImage=pickedImage.fixedOrientation()
        //profileImg.image = fixOrientationImage
        self.imageProfile.contentMode = .scaleToFill
        self.imageProfile.image=fixOrientationImage
       // self.imageProfile.image = pickedImage
    }
    dismiss(animated: true, completion: nil)
}

如何从pickedImage.fixedOrientation()中的自定义按钮调用此功能imagePickerController

UIImage的扩展

func fixedOrientation() -> UIImage {
    if imageOrientation == .up { return self }

    var transform:CGAffineTransform = .identity
    switch imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: size.width, y: size.height).rotated(by: .pi)
    case .left, .leftMirrored:
        transform = transform.translatedBy(x: size.width, y: 0).rotated(by: .pi/2)
    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: size.height).rotated(by: -.pi/2)
    default: break
    }

    switch imageOrientation {
    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: size.width, y: 0).scaledBy(x: -1, y: 1)
    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: size.height, y: 0).scaledBy(x: -1, y: 1)
    default: break
    }

    let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
                        bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0,
                        space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue)!
    ctx.concatenate(transform)

    switch imageOrientation {
    case .left, .leftMirrored, .right, .rightMirrored:
        ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height,height: size.width))
    default:
        ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width,height: size.height))
    }
    return UIImage(cgImage: ctx.makeImage()!)
}

1 个答案:

答案 0 :(得分:0)

 //create btn add set properties
    let btn = UIButton(type: .custom)
    btn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    btn.addTarget(self, action: #selector(customBtnTapped(_:)), for: .touchUpInside)

    //set bar button item
    let barbutton = UIBarButtonItem(customView: btn)
    self.navigationItem.leftBarButtonItem = barbutton

自定义按钮操作方法

@objc fileprivate func customBtnTapped(_ sender: UIButton) {
    let img = self.fixedOrientation()
}