剛開始工作的時候因為安卓不能識別高清分辨圖,iOS上傳后安卓獲取會崩潰匆骗,所以用的
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo這個老方法澄港,這個方法在3.0棄用了椒涯,但在工程中并不影響使用。今天突然心血來潮試著改寫一下【獲取相冊后圖片回調】回梧。
在獲取相冊后圖片回調的方法用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *ima = info[UIImagePickerControllerEditedImage];
//用的是UIImageExt 這個工具類
ima = [UIImageExt setAvatarForNewSize:ima];
[self dismissViewControllerAnimated:YES completion:^{
}];
self.titleImageView.layer.cornerRadius = 20 * Width;
//如果是button上的圖片的話
[self.headButton setImage:[image imageWithRenderingMode:1] forState:UIControlStateNormal];
}
UIImageExt 工具類【我在原有的這個封裝好的工類里面添加一個類方法setAvatarForNewSize】
+ (UIImage *)setAvatarForNewSize:(UIImage *)image {
CGSize origImageSize = image.size;
// new image size needed, which is picked by the image picker
CGFloat newWidth = kScreenWidth;
CGFloat newHeight = (newWidth * origImageSize.height) / origImageSize.width;
CGRect newRect = CGRectMake(0, 0, newWidth, newHeight);
// make sure that zoom ratio stays original value
float ratio = MAX(newRect.size.width / origImageSize.width, newRect.size.height / origImageSize.height);
// create a lucency bitmap context via current screen scaling factor
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
// make the new image be in the center in the draw zoom
CGRect projectRect;
projectRect.size.width = ratio * origImageSize.width;
projectRect.size.height = ratio * origImageSize.height;
projectRect.origin.x = (newRect.size.width - projectRect.size.width) * 0.5;
projectRect.origin.y = (newRect.size.height - projectRect.size.height) * 0.5;
// draw the new picture in the new rect
[image drawInRect:projectRect];
// get the image we need
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
// clean up image context
UIGraphicsEndImageContext();
return smallImage;
}
這樣在系統(tǒng)相冊獲取圖片的清晰辨識就會搞了許多废岂。
實現(xiàn)原理,就是用圖形上下文把原圖按長寬比例繪制成原來長寬比屏幕大小的圖片狱意,然后再截取新圖湖苞,可能以前是1000:2000的分辨率,給縮成100:200了详囤,細節(jié)基本沒變化