2014.5.26
UIImageの画像の拡大・縮小・反転・回転
UIImageの画像をリサイズ、回転、反転したい場合がある。こんなときにはQuartz 2D APIを使用する。Quartz 2D APIはCore Graphicsフレームワークの一部。
CTM(Current Transformation Matrix)を使う。主に以下の3つ。
CGContextTranslateCTM : 原点の平行移動 CGContextRotateCTM : 原点を中心として座標系を回転 CGContextScaleCTM : 原点を中心として座標系を拡大縮小
①とりあえずそのまま描画
- (UIImage*)drawImage { UIImage *original_img = [UIImage imageNamed:@"frog"]; UIGraphicsBeginImageContext(self.view.bounds.size); [original_img drawInRect:CGRectMake(0, 0, original_img.size.width, original_img.size.height)]; UIImage *final_img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return final_img; }
②画像を平行移動させて描画する場合 CGContextTranslateCTMで座標系を平行移動
- (UIImage*)drawImageWithTranslateCTM { UIImage *original_img = [UIImage imageNamed:@"frog"]; UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 100, 100); [original_img drawInRect:CGRectMake(0, 0, original_img.size.width, original_img.size.height)]; UIImage *final_img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return final_img; }
③画像を回転させて描画する場合 CGContextRotateCTMで座標系を回転
- (UIImage*)drawImageWithRotateCTM { UIImage *original_img = [UIImage imageNamed:@"frog"]; UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextRotateCTM(context, 30 * M_PI/180); [original_img drawInRect:CGRectMake(0, 0, original_img.size.width, original_img.size.height)]; UIImage *final_img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return final_img; }
④画像を縮小して描画する場合 CGContextScaleCTMで座標系を縮小
- (UIImage*)drawImageWithScaleCTM { UIImage *original_img = [UIImage imageNamed:@"frog"]; UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextScaleCTM(context, 0.5, 0.5); [original_img drawInRect:CGRectMake(0, 0, original_img.size.width, original_img.size.height)]; UIImage *final_img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return final_img; }
④画像を反転して描画する場合 CGContextScaleCTMで座標系をマイナス方向に拡大してCGContextTranslateCTMで平行移動
- (UIImage*)drawImageInverted{ UIImage *original_img = [UIImage imageNamed:@"frog"]; UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextScaleCTM(context, -1, 1.0); CGContextTranslateCTM(context, -self.view.bounds.size.width, 0); [original_img drawInRect:CGRectMake(0, 0, original_img.size.width, original_img.size.height)]; UIImage *final_img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return final_img; }
Related Posts
Popular Posts
- 2014-11-29
- 2021-01-30
- 2014-03-02
- 2017-08-15
- 2019-03-20
Recent Posts
- 2023-1-7
- 2022-10-8
- 2022-8-1
- 2022-3-12
- 2022-1-5