您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 圖片展示、縮放、移動與裁切實作

編輯:iOS 相關資訊

在 iOS 中展示圖片時,除了單純顯示,還常需要縮放、移動與裁切。這類互動常用於圖片預覽、文件掃描或影像辨識前的範圍選擇。

建立圖片視圖

先將圖片載入 UIImageView,並將視圖尺寸設為圖片原始尺寸,讓內容完整呈現。

UIImage *image = [UIImage imageNamed:@"sample.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.view addSubview:imageView];

縮放圖片

可以使用 UIPinchGestureRecognizer 處理雙指縮放,透過 transform 調整視圖比例。

CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
imageView.transform = transform;

移動圖片

使用 UIPanGestureRecognizer 可以讓使用者拖曳畫面。

CGPoint location = [gesture locationInView:self.view];
imageView.center = location;

擷取畫面

若需要對目前顯示區域進行裁切,可以先把畫面渲染成 UIImage。

UIGraphicsBeginImageContext(view.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

裁切指定區域

取得截圖後,可以使用 CGImageCreateWithImageInRect 裁切。

CGRect cropRect = CGRectMake(x, y, width, height);
CGImageRef imageRef = CGImageCreateWithImageInRect([snapshot CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

手勢框選

若希望使用者以手指畫出矩形範圍,可以自訂 UIView,在 touchesBegan、touchesMoved 與 touchesEnded 中記錄座標,並以 UIBezierPath 或 Core Graphics 繪製外框。最後將框選範圍轉成 CGRect,再進行裁切。

這類功能的關鍵在於座標系一致性。只要縮放、移動與截圖的座標轉換處理得當,就能穩定地做出直覺的裁切體驗。

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