回答編集履歴

1

s

2018/06/21 20:49

投稿

_Kentarou
_Kentarou

スコア8490

test CHANGED
@@ -73,3 +73,169 @@
73
73
  @end
74
74
 
75
75
  ```
76
+
77
+
78
+
79
+ 回答追記
80
+
81
+ ---
82
+
83
+
84
+
85
+ 画面の幅にから`20px`づつ控えられたサイズで画像の幅を固定して、その比率に合わせて高さを計算して画像をリサイズして、最後に角丸にするコードを書いてみました。
86
+
87
+ ※ 幅を基準にしているので横長の画像は大丈夫ですが、縦長の画像だと下にはみ出す可能性があります、あとは好きなように調整してください。
88
+
89
+
90
+
91
+ 参考にしてみてください。
92
+
93
+
94
+
95
+ ```
96
+
97
+ // ViewController.h
98
+
99
+ #import <UIKit/UIKit.h>
100
+
101
+
102
+
103
+ @interface ViewController : UIViewController
104
+
105
+
106
+
107
+ @end
108
+
109
+
110
+
111
+
112
+
113
+ @interface UIImage (Additional)
114
+
115
+ - (UIImage*) btk_ImageResized : (CGSize)size;
116
+
117
+ @end
118
+
119
+ ```
120
+
121
+
122
+
123
+ ```
124
+
125
+ // ViewController.m
126
+
127
+
128
+
129
+ #import "ViewController.h"
130
+
131
+
132
+
133
+ @interface ViewController ()
134
+
135
+
136
+
137
+ @end
138
+
139
+
140
+
141
+ @implementation ViewController
142
+
143
+
144
+
145
+ - (void)viewDidLoad {
146
+
147
+ [super viewDidLoad];
148
+
149
+
150
+
151
+ CGFloat imageMargin = 20;
152
+
153
+ CGFloat width = [UIScreen mainScreen].bounds.size.width - imageMargin * 2;
154
+
155
+
156
+
157
+ UIImage *image = [UIImage imageNamed:@"mm2"];
158
+
159
+ CGFloat imageWidth = image.size.width;
160
+
161
+ CGFloat imageHeight = image.size.height;
162
+
163
+
164
+
165
+ CGFloat w = width / imageWidth;
166
+
167
+ CGFloat h = imageHeight * w;
168
+
169
+
170
+
171
+ // 画像リサイズ
172
+
173
+ UIImage * resizeImage = [image btk_ImageResized:CGSizeMake(width, h)];
174
+
175
+
176
+
177
+ //UIImageViewの生成
178
+
179
+ UIImageView *imageView = [[UIImageView alloc] initWithImage: resizeImage];
180
+
181
+ imageView.frame = CGRectMake(20, 100, width, h);
182
+
183
+ imageView.contentMode = UIViewContentModeScaleAspectFit;
184
+
185
+ [self.view addSubview:imageView];
186
+
187
+
188
+
189
+ [imageView layer].masksToBounds = YES;
190
+
191
+ [imageView layer].cornerRadius = 10;
192
+
193
+ }
194
+
195
+ @end
196
+
197
+
198
+
199
+
200
+
201
+ @implementation UIImage (Additional)
202
+
203
+
204
+
205
+ - (UIImage*) btk_ImageResized : (CGSize)size
206
+
207
+ {
208
+
209
+ if(CGSizeEqualToSize(self.size, size) && self.imageOrientation == UIImageOrientationUp){
210
+
211
+ // No need to resize nor convert orientation
212
+
213
+ return self;
214
+
215
+ }
216
+
217
+ UIGraphicsBeginImageContext(size);
218
+
219
+ @try {
220
+
221
+ CGContextRef context = UIGraphicsGetCurrentContext();
222
+
223
+ CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
224
+
225
+ [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
226
+
227
+ return UIGraphicsGetImageFromCurrentImageContext();
228
+
229
+ }
230
+
231
+ @finally {
232
+
233
+ UIGraphicsEndImageContext();
234
+
235
+ }
236
+
237
+ }
238
+
239
+ @end
240
+
241
+ ```