歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS 截取部分圖片並顯示

iOS 截取部分圖片並顯示

日期:2017/3/1 9:58:31   编辑:Linux編程

在ios開發中,肯定會碰到需要截取部分圖片的情況。

最終的效果類似這樣:

先看最原始的示例,顯示完整的圖片

寫了個最簡單的讀取圖片並顯示的代碼,打算以此為開始,逐漸實現截取部分圖片的功能。

代碼主要是,在控制器代碼中:

- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide];
UIImage *image=[UIImage imageNamed:@"1.jpg"];

UIImageView *contentView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[contentView setImage:image];

self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:contentView];
}

另外,應該有一個名為1.jpg的768×1024的圖片(我這裡是iPad)。

截取整個圖片

可以認為截取整個圖片是截取部分圖片的一個特例。對ios不熟嘛,因此打算很謹慎的推進。截取整個圖片可以減少中間的復雜性。

根據API,摸索著寫了一個示例,效果出乎意料:

代碼:

- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide];
UIImage *image=[UIImage imageNamed:@"1.jpg"];

UIImageView *contentView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//[contentView setImage:image];

CGRect rect = CGRectMake(0, 0, 768, 1024);//創建矩形框
UIGraphicsBeginImageContext(rect.size);//根據size大小創建一個基於位圖的圖形上下文
CGContextRef currentContext = UIGraphicsGetCurrentContext();//獲取當前quartz 2d繪圖環境
CGContextClipToRect( currentContext, rect);//設置當前繪圖環境到矩形框

CGContextDrawImage(currentContext, rect, image.CGImage);//繪圖
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();//獲得圖片
UIGraphicsEndImageContext();//從當前堆棧中刪除quartz 2d繪圖環境

contentView.image=cropped;

self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:contentView];

[cropped release];
}

這個代碼說明了兩點:

  • 好的方面:說明我的代碼起作用了,確實截取了所需的圖形
  • 壞的方面:圖形是顛倒的,而且是鏡像的。

問題應該出在坐標系上。下面畫了一個quartz 2d的坐標系,坐標原點在左下角:

因此以這個坐標系取圖形,就會有轉向180°的效果。

Copyright © Linux教程網 All Rights Reserved