如何输出没有背景的图像?

问题描述 投票:0回答:1

我有一个canvasImageView并在上面绘制了一些东西。而且我要输出的图像仅包含图像区域。我的输出功能是func saveBtnPressed(sender: UIButton)。如下图所示,我要输出蓝线区域。有任何想法吗?谢谢。

output image

class CanvasViewController: UIViewController {

    let canvasImageView: CanvasImageView = {
        let ui = CanvasImageView()
        ui.contentMode = .scaleAspectFit
        ui.layer.backgroundColor = UIColor.clear.cgColor
        ui.backgroundColor = UIColor.clear
        ui.clipsToBounds = true
        ui.isMultipleTouchEnabled = false
        ui.isUserInteractionEnabled = true
        return ui
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Color Yourself"

        let save = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveBtnPressed(sender:)))
        let redo = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(clearBtnPressed(sender:)))
        let back = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(cancelBtnPressed(sender:)))

        self.navigationItem.rightBarButtonItems = [save, redo]
        self.navigationItem.leftBarButtonItem = back

        self.setupView()
    }

    fileprivate func setupView() {

        self.view.addSubview(canvasImageView)

        if #available(iOS 11.0, *) {
            self.canvasImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        } else {
            self.canvasImageView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 0).isActive = true
        }

        self.canvasImageView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
        }

    }

    //MARK: BUTTON ACTION

    @objc func cancelBtnPressed(sender: UIBarButtonItem) {
        self.dismiss(animated: false, completion: nil)
    }

    @objc func clearBtnPressed(sender: UIButton) {
        canvasImageView.clearCanvas()
    }

    @objc func saveBtnPressed(sender: UIButton) {

        //Here is output image.
        UIGraphicsBeginImageContextWithOptions(self.canvasImageView.layer.bounds.size, true, 0.0)
        self.canvasImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if let img = image {
            UIImageWriteToSavedPhotosAlbum(img, self,#selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
        }

    }    
}
class CanvasImageView: UIImageView {

    var lineColor = UIColor.red
    var lineWidth: CGFloat = 10
    var path: UIBezierPath?
    var touchPoint: CGPoint!
    var startingPoint: CGPoint!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        self.startingPoint = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.touchPoint = touches.first?.location(in: self)
        self.path = UIBezierPath()
        path?.move(to: startingPoint)
        path?.addLine(to: touchPoint)
        self.startingPoint = touchPoint
        self.draw()
    }

    func draw() {
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path?.cgPath
        shapeLayer.strokeColor = lineColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.fillColor = UIColor.clear.cgColor
        self.layer.addSublayer(shapeLayer)
        self.setNeedsDisplay()
    }

    func clearCanvas() {
        guard let drawPath = path else { return }
        drawPath.removeAllPoints()
        self.layer.sublayers = nil
        self.setNeedsDisplay()
    }
}
ios swift calayer
1个回答
0
投票

您必须裁剪所需的像

  func cropImage(image: UIImage, toRect: CGRect) -> UIImage? {
    // Cropping is available trhough CGGraphics
    let cgImage :CGImage! = image.cgImage
    let croppedCGImage: CGImage! = cgImage.cropping(to: toRect)

    return UIImage(cgImage: croppedCGImage)
}

这将失去您必须重新绘制图像的质量

func makeLargeView(view: UIView, scale: CGFloat,imageToShare:UIImage) -> UIView
{

    let constrains = self.designView.constraints
    self.designView.removeConstraints(constrains)
    let viewData = NSKeyedArchiver.archivedData(withRootObject: view)
    let unarchiveData = NSKeyedUnarchiver.unarchiveObject(with: viewData) as! UIView

    self.designView.addConstraints(constrains)

    let mainViewFrame = unarchiveData.frame
    unarchiveData.removeConstraints(unarchiveData.constraints)
    let mainViewNewFrame = CGRect(x: 0, y: 0, width: mainViewFrame.width*scale, height: mainViewFrame.height*scale)
    unarchiveData.frame = mainViewNewFrame

    for subview in unarchiveData.subviews
    {
        let oldFrame = subview.frame
        let newFrame = CGRect(x: oldFrame.origin.x*scale, y: oldFrame.origin.y*scale, width: oldFrame.width*scale, height: oldFrame.height*scale)
        subview.frame = newFrame
        subview.widthAnchor.constraint(equalToConstant: mainViewNewFrame.width).isActive = true
        subview.heightAnchor.constraint(equalToConstant: mainViewNewFrame.height).isActive = true
        if subview is UIScrollView{
            if let imgView = subview.subviews[0] as? UIImageView{

                imgView.frame = CGRect(x: unarchiveData.frame.origin.x, y: unarchiveData.frame.origin.y, width: oldFrame.width*scale, height: oldFrame.height*scale)
                imgView.widthAnchor.constraint(equalToConstant: mainViewNewFrame.width ).isActive = true
                imgView.heightAnchor.constraint(equalToConstant: mainViewNewFrame.height).isActive = true

            }
        }
    unarchiveData.widthAnchor.constraint(equalToConstant: mainViewNewFrame.width).isActive = true
    unarchiveData.heightAnchor.constraint(equalToConstant: mainViewNewFrame.height).isActive = true
    return unarchiveData
}

您必须根据自己的情况处理子视图

© www.soinside.com 2019 - 2024. All rights reserved.