您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

圖片縮放、拖動與自定義裁剪區域的完整實作

編輯:iOS 開發綜合

做圖像識別類功能時,常常需要讓用戶先放大縮小、拖動調整,然後在屏幕上框出一塊區域交給識別引擎。這樣做的好處很明確:把真正需要識別的文字內容放大並拉進可見區域,能顯著提升識別效率。本文把整個流程拆開來講。

一、加載圖片並鋪滿界面

先把圖片讀進 UIImage,掛到一個 UIImageView 上,並讓 imageView 的尺寸與圖片原始尺寸一致,這樣才能保證圖片完整展現,也便於後續計算。

// 從文件加載圖片
UIImage *image = [UIImage imageNamed:@"prgBBinary.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

// 取得圖片原始尺寸
CGSize size = [image size];

// 讓 imageView 按原始尺寸鋪開
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];

這樣一來,超出了屏幕範圍的部分就無法直接看到,需要靠縮放與移動來瀏覽。

二、用 pan 手勢拖動視圖

拖動邏輯很簡單:在移動中或移動結束時,把手勢當前位置作為視圖中心。

- (void)pan:(UIPanGestureRecognizer *)gesture
{
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {

        CGPoint location = [gesture locationInView:[self superview]];
        [self setCenter:location];
    }
}

三、用 pinch 手勢縮放視圖

縮放靠 CGAffineTransform 完成。這裡用兩個變量記錄狀態:mLastScale 保存上一次手勢的比例值,mCurrentScale 保存累積後的總比例。每次回調只取增量,避免比例跳變。

-(void)handlePinch:(UIPinchGestureRecognizer*)sender
{
    NSLog(@"lastscale = %f", mLastScale);

    mCurrentScale += [sender scale] - mLastScale;
    mLastScale = [sender scale];

    if (sender.state == UIGestureRecognizerStateEnded) {
        mLastScale = 1.0;
    }

    CGAffineTransform currentTransform = CGAffineTransformIdentity;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, mCurrentScale, mCurrentScale);
    mGestureView.transform = newTransform;
}

手勢結束時把 mLastScale 重置為 1.0,這樣下一次手勢從新的基線開始累計。

四、縮放後需要「截屏」再裁剪

這是最容易踩坑的地方:縮放只是改變了 view 的 transform,底層的圖片數據並沒有變。如果直接拿原圖去裁剪,得到的永遠是原圖區域,跟用戶眼睛看到的畫面完全對不上。

而裁剪本身只能在可見區域內進行,所以必須先把當前屏幕內容渲染成一張新圖,再對這張圖做裁剪。

- (UIImage *)imageWithUIView:(UIView *)view
{
    CGSize screenShotSize = view.bounds.size;
    UIImage *img;

    UIGraphicsBeginImageContext(screenShotSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    img = UIGraphicsGetImageFromCurrentImageContext();

    CGContextRestoreGState(context);
    UIGraphicsEndImageContext();

    return img;
}

五、讓用戶手勢畫出矩形框

方案一是用 UIBezierPath 畫矩形,路徑閉合後就是一個框:

UIBezierPath *aPath = [UIBezierPath bezierPath];
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
[aPath addLineToPoint:CGPointMake(200.0, 0.0)];
[aPath addLineToPoint:CGPointMake(200.0, 140.0)];
[aPath addLineToPoint:CGPointMake(0.0, 140.0)];
[aPath closePath];

實作一個 UIView 子類,在 touchesMoved 中不斷把路徑延長,就能畫出跟手的矩形:

@implementation MyLineDrawingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        myPath = [[UIBezierPath alloc] init];
        myPath.lineCapStyle = kCGLineCapRound;
        myPath.miterLimit = 0;
        myPath.lineWidth = 10;
        brushPattern = [UIColor redColor];
    }
    return self;
}

// 只有自定義繪製時才需要重寫 drawRect:
- (void)drawRect:(CGRect)rect
{
    [brushPattern setStroke];
    [myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

#pragma mark - Touch Methods

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *mytouch = [[touches allObjects] objectAtIndex:0];
    [myPath moveToPoint:[mytouch locationInView:self]];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *mytouch = [[touches allObjects] objectAtIndex:0];
    [myPath addLineToPoint:[mytouch locationInView:self]];
    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [myPath closePath];
    [self setNeedsDisplay];
}

@end

方案二是繞過 UIBezierPath,直接用 Core Graphics 的 API 畫線。這種方式適合需要精確控制起止點的場景(比如只畫一個從起點到當前手指位置的矩形對角線):

@implementation GestureView
{
    CGPoint _originOfTouchPoint;        // touchesBegan 中記錄的起點
    CGPoint _currentFingerPositionPoint; // 手指當前拖到的位置
    CGFloat _strokeWidth;               // 線寬
    id _touchStartedObject;             // 首次觸摸命中的視圖
}

// 若用 Interface Builder 設計界面,nib 中的對象通過 initWithCoder: 初始化
- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self) {
        _originOfTouchPoint = CGPointMake(0.0, 0.0);
        _currentFingerPositionPoint = CGPointMake(100.0, 100.0);
        _strokeWidth = 2.0;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetLineWidth(context, _strokeWidth);

    // 起點
    CGContextMoveToPoint(context, _originOfTouchPoint.x, _originOfTouchPoint.y);
    // 終點
    CGContextAddLineToPoint(context, _currentFingerPositionPoint.x, _currentFingerPositionPoint.y);
    // 描繪
    CGContextStrokePath(context);
}

#pragma mark touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _originOfTouchPoint = [[touches anyObject] locationInView:self];
    _touchStartedObject = [[touches anyObject] view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint movedToPoint = [[touches anyObject] locationInView:self];
    if (CGPointEqualToPoint(movedToPoint, _currentFingerPositionPoint) == NO) {
        _currentFingerPositionPoint = movedToPoint;
        [self setNeedsDisplay];   // 觸發 drawRect: 重繪
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    _originOfTouchPoint = CGPointZero;
    _currentFingerPositionPoint = CGPointZero;
    _touchStartedObject = nil;
}

@end

六、算出矩形的 frame 並裁剪

有了矩形框之後,怎麼拿到它的 frame?做法是在拖動過程中記錄所涉全部點裡 X 與 Y 的最大值和最小值,兩兩組合即得包圍矩形。手勢結束、矩形重新繪製完成後,就能得到圖像上的矩形區域與 frame 值。

拿到 frame 後,用 CGImageCreateWithImageInRect 從截屏圖中裁出對應區域,再包成 UIImage 掛到新的 UIImageView 上:

// 構造要裁剪的矩形(此處以居中一半區域為例)
CGRect rect = CGRectMake(size.width / 4, size.height / 4,
                         (size.width / 2), (size.height / 2));

// 從原圖數據中按矩形生成位圖
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

// 展示裁剪結果
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(0, 200, (size.width / 2), (size.height / 2))];
[[self view] addSubview:imageView];
[imageView release];

注意 CGImageRelease 不能漏——CGImageRef 是 C 風格的 Core Graphics 對象,不受 ARC 管理,必須手動釋放,否則反覆裁剪會持續洩露內存。

最後提醒一句:以上代碼是基於思路與資料整理的參考實現,並未逐行編譯測試,請結合自身工程實際情況調整後使用。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved