iOS 自定义裁剪相册照片(Swift和OC双版)

设计要求
1、传入照片
2、保留边距,初始化居中铺满高亮区域
3、自由点缩放,铺满全屏
4、裁剪方形图片

Swift 版本

框选封面图.png

可直接使用 Swift 源码

import Foundation

struct TailorImageLayout {
    static let boardWidth = 1.0
    static let topMargin = 90
    static let kUIScaleX = UIDevice.screenWidth / 375.0
    static let contentInsetLeft = ceil(60.0 * kUIScaleX) - boardWidth
    static let contentWidth = UIDevice.screenWidth - 2 * contentInsetLeft
    static let contentInsetTop = ceil((UIDevice.screenHeight - contentWidth) * 0.5 - Double(topMargin) - boardWidth)
    static let hollowSize = CGSize(width: contentWidth, height: contentWidth)
}

class TailorImageViewController: BaseViewController {
    private var isFirstZoom = false
    var originImage: UIImage?
    var closeAction: (() -> Void)?
    var tailorImageAction: ((UIImage) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        createSubviews()
        
        bottomView.cancelAction = { [weak self] in
            self?.closeAction?()
        }
        
        bottomView.comfireAction = { [weak self] in
            if let tailorImage = self?.getSubImage() {
                self?.tailorImageAction?(tailorImage)
            } else {
                Toast.show("图片裁剪失败")
            }
        }
        
        if let originImage = originImage {
            image = originImage
        }
    }
    
    private var image: UIImage? {
        didSet {
            guard let image = image else { return }
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.imageView.image = image
                let maxSize = scrollView.frame.size
                let widthRatio = maxSize.width / image.size.width
                let heightRatio = maxSize.height / image.size.height
                var initialZoom = min(widthRatio, heightRatio)
                initialZoom = min(initialZoom, 1.0)
                
                var initialFrame = self.scrollView.frame
                initialFrame.size.width = image.size.width * initialZoom
                initialFrame.size.height = image.size.height * initialZoom
                self.imageView.frame = initialFrame
                
                self.isFirstZoom = true
                self.scrollView.minimumZoomScale = initialZoom
                self.scrollView.maximumZoomScale = 5.0
                self.scrollView.zoomScale = 1.0
                self.scrollViewDidZoom(self.scrollView)
            }
        }
    }
    
    // MARK: - UI布局
    private func createSubviews() {
        scrollView.frame = CGRect(x: 0,
                                  y: TailorImageLayout.topMargin,
                                  width: Int(UIDevice.screenWidth),
                                  height: Int(UIDevice.screenHeight) - 2 * TailorImageLayout.topMargin)
        view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.contentInset = UIEdgeInsets(top: TailorImageLayout.contentInsetTop,
                                               left: TailorImageLayout.contentInsetLeft,
                                               bottom: TailorImageLayout.contentInsetTop,
                                               right: TailorImageLayout.contentInsetLeft)
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.height.equalTo(TailorImageLayout.topMargin)
            make.left.right.bottom.equalToSuperview()
        }
        
        view.addSubview(maskView)
        maskView.snp.makeConstraints { make in
            make.edges.equalTo(scrollView)
        }
    }
    
    private lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .darkGray
        scroll.showsHorizontalScrollIndicator = false
        scroll.showsVerticalScrollIndicator = false
        scroll.contentInsetAdjustmentBehavior = .never
        scroll.bouncesZoom = false
        scroll.delegate = self
        return scroll
    }()
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private lazy var maskView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "TailorImageMask"))
        imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private var bottomView = TailorImageBottomView()
}

// MARK: - 缩放 & 拖动
extension TailorImageViewController: UIScrollViewDelegate {
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        var wContent = scrollView.contentSize.width
        var hContent = scrollView.contentSize.height
        
        if wContent <= 0 {
            wContent = TailorImageLayout.hollowSize.width * 0.5
        }
        
        if hContent <= 0 {
            hContent = TailorImageLayout.hollowSize.height * 0.5
        }
        
        if wContent < TailorImageLayout.hollowSize.width {
            hContent = hContent * TailorImageLayout.hollowSize.width / wContent
            wContent = TailorImageLayout.hollowSize.width
        }
        
        if hContent < TailorImageLayout.hollowSize.height {
            wContent = wContent * TailorImageLayout.hollowSize.height / hContent
            hContent = TailorImageLayout.hollowSize.height
        }
        
        imageView.frame.size.width = wContent
        imageView.frame.size.height = hContent
        
        scrollView.contentSize = CGSize(width: wContent, height: hContent)
        imageView.center = CGPoint(
            x: scrollView.contentSize.width * 0.5,
            y: scrollView.contentSize.height * 0.5
        )
        
        if isFirstZoom {
            let showSize = TailorImageLayout.hollowSize
            let offsetX = (imageView.frame.width - showSize.width) * 0.5 - TailorImageLayout.contentInsetLeft
            let offsetY = (imageView.frame.height - showSize.height) * 0.5 - TailorImageLayout.contentInsetTop
            scrollView.setContentOffset(CGPoint(x: offsetX, y: offsetY), animated: false)
            isFirstZoom = false
        }
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        imageView
    }
}

// MARK: - 高精度 裁剪逻辑
extension TailorImageViewController {
    private func getSubImage() -> UIImage? {
        guard imageView.image != nil else { return nil }
        let hollowSize = TailorImageLayout.hollowSize
        guard hollowSize.width > 0 && hollowSize.height > 0 else { return nil }

        let insetLeft = TailorImageLayout.contentInsetLeft
        let insetTop = TailorImageLayout.contentInsetTop
        let offset = scrollView.contentOffset
        
        let format = UIGraphicsImageRendererFormat.default()
        format.scale = UIScreen.main.scale
        format.opaque = true
        let renderer = UIGraphicsImageRenderer(size: hollowSize, format: format)

        let img = renderer.image { ctx in
            ctx.cgContext.translateBy(x: -(offset.x + insetLeft), y: -(offset.y + insetTop))
            scrollView.layer.render(in: ctx.cgContext)
        }
        return img
    }
}


class TailorImageBottomView: BaseView {
    
    var cancelAction: (() -> Void)?
    var comfireAction: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .black
        createSubviews()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI布局
    private func createSubviews() {
        addSubview(cancelButton)
        cancelButton.snp.makeConstraints { make in
            make.height.equalTo(28)
            make.width.equalTo(66)
            make.leading.equalToSuperview().inset(24)
            make.centerY.equalToSuperview()
        }
        addSubview(comfireButton)
        comfireButton.snp.makeConstraints { make in
            make.height.equalTo(28)
            make.width.equalTo(66)
            make.trailing.equalToSuperview().inset(24)
            make.centerY.equalToSuperview()
        }
        
        cancelButton.addAction(UIAction { [weak self] _ in
            self?.cancelAction?()
        }, for: .touchUpInside)
        
        comfireButton.addAction(UIAction { [weak self] _ in
            self?.comfireAction?()
        }, for: .touchUpInside)
    }
    
    fileprivate lazy var cancelButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("取消", for: .normal)
        button.titleLabel?.font = UIFont.ai.medium(.size14)
        button.setTitleColor(UIColor("#CACBCF"), for: .disabled)
        return button
    }()
    
    fileprivate lazy var comfireButton: UIButton = {
        let button = UIButton(type: .custom)
        button.layer.cornerRadius = 14
        button.layer.masksToBounds = true
        button.setTitle("确认", for: .normal)
        button.titleLabel?.font = UIFont.ai.medium(.size14)
        button.setTitleColor(.black, for: .normal)
        button.backgroundColor = UIColor("#FFD801")
        return button
    }()
}

蒙层图片


蒙版.png

OC版

image.png

image.png

一、视图层级搭建

1、最底层是UIScrollview,UIScrollview上放置UIimageView。
2、和UIScrollview同父视图,创建自定义navbarView。
3、和UIScrollview同父视图,创建一个mask模糊层,禁用手势,模糊层可以使用layer图层实现,或用4块小视图拼接都行。


- (void)createSubviews
{
    //注意: 此处不要使用约束布局,因为scrollview存在缩、滚动、弹簧动画等混合效果,使用约束计算容易崩溃
    self.scrollView.frame = CGRectMake(0, 0, DD_SCREEN_WIDTH, DD_SCREEN_HEIGHT);
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    self.scrollView.contentInset =
    UIEdgeInsetsMake(self.contentInsetTop, self.contentInsetLeft, self.contentInsetTop, self.contentInsetLeft);
   
    [self.view addSubview:self.navBarView];
    [self.navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(navBarHeight);
    }];
   //镂空蒙层
    [self.view addSubview:self.maskView];
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(navBarHeight);
    }];
}

二、功能实现

1、读取照片

推荐使用iOS7新框架photokit。
注意:读取相册照片时,系统会两次回调resultHandler,第一次传出缩略图(模糊图),第二次会传出高清图(图片数据不完整时,存在回传失败,image为nil),要做校验处理。

- (void)setAssetPh:(PHAsset *)assetPh
{
    _assetPh = assetPh;
    self.image = nil;
    self.viewIndicator.hidden = NO;
    [self.viewIndicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHImageRequestOptions *option = [PHImageRequestOptions new];
        option.synchronous = NO;
        [[DDWPhotoImageManger sharedInstance]  requestImageForAsset:assetPh targetSize:[DDWimagePickerManger sharedInstance].getImageSizeOfBrower contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        //图片有可能读取失败,要做校验
            if (result) {
                self.image = result;
            }
            [self.viewIndicator stopAnimating];
            self.viewIndicator.hidden = YES;
        }];
    });
}

2、初始化UI 照片居中,铺满显示

- (void)setImage:(UIImage *)image
{
    if (image != _image) {
        _image = image;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = image;
            CGSize maxSize = self.hollowSize;
            CGFloat widthRatio = maxSize.width / image.size.width;
            CGFloat heightRatio = maxSize.height / image.size.height;
            CGFloat initialZoom = (widthRatio > heightRatio) ? heightRatio : widthRatio;
            if (initialZoom > 1) {
                initialZoom = 1;
            }
            // 初始化显示imageView
            CGRect  initialFrame = self.scrollView.frame;
            initialFrame.size.width = image.size.width * initialZoom;
            initialFrame.size.height = image.size.height * initialZoom;
            self.imageView.frame = initialFrame;
            
            [self.scrollView setMinimumZoomScale:initialZoom];
            [self.scrollView setMaximumZoomScale:5];
            //初次铺满缩放
            self.isFirstZoom = YES;
            [self.scrollView setZoomScale:1.0];
            [self scrollViewDidZoom:self.scrollView];
        });
    }
}

3、自由点缩放

实现UIScrollViewDelegate的缩放方法,

#pragma mark- <UIScrollViewDelegate> Methods
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat w_content = self.scrollView.contentSize.width;
    CGFloat h_content = self.scrollView.contentSize.height;

    //容错处理
    if (w_content <= 0) {
        w_content = self.hollowSize.width * 0.5;
    }
    if (h_content <= 0) {
        h_content = self.hollowSize.height * 0.5;
    }
    
    //限定铺满处理
    if (w_content < self.hollowSize.width) {
        h_content = h_content * self.hollowSize.width / w_content;
        w_content = self.hollowSize.width;
    }
    if (h_content < self.hollowSize.height) {
        w_content = w_content * self.hollowSize.height / h_content;
        h_content = self.hollowSize.height;
    }
    self.imageView.width = w_content;
    self.imageView.height = h_content;
    self.scrollView.contentSize = CGSizeMake(w_content, h_content);
    self.imageView.center = CGPointMake(self.scrollView.contentSize.width * 0.5 ,
                                        self.scrollView.contentSize.height * 0.5);
    if (self.isFirstZoom) {
       // 初始化缩放居中显示
        CGFloat offset_x = (self.imageView.frame.size.width - self.hollowSize.width) * 0.5 - self.contentInsetLeft;
        CGFloat offset_y = (self.imageView.frame.size.height - self.hollowSize.height) * 0.5 - self.contentInsetTop;
        [self.scrollView setContentOffset:CGPointMake(offset_x , offset_y) animated:NO];
        self.isFirstZoom = NO;
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

4、裁剪指定区域为图片

调用系统裁剪方法即可。

#pragma mark- 裁剪 Methods
- (UIImage *)getSubImage
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.hollowSize.width, self.hollowSize.height), YES, [UIScreen mainScreen].scale);
    CGPoint offset = self.scrollView.contentOffset;
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -(offset.x + self.contentInsetLeft), -(offset.y + self.contentInsetTop));
    [self.scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    img = [self imageWithImage:img scaledToSize:CGSizeMake(self.hollowSize.width, self.hollowSize.height)];
    return img;
}

-(UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。