Image is not fit into circle UIImageview in iOS Objective-C? - objective-c

I know it's a common question but i am stack to implement it. I have an imageview which weight and height are equal. When I pick an image from media library some image are fit into circle but some image not fit into circle imageview.
Can any one suggest me how to set any type of image set into circle image view?
Because I want to implement to user can set his/her profile image. so user insert any type of image or any resolution, I need to crop that image but I am not able to do this. And also I don't prefer any 3rd library.
Here is my code:
-(void)btnImgAct //Button Action
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary])
{
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)Info
{
UIImage *pickerImage=[[UIImage alloc]init];
pickerImage=image;
imageDataPicker =[[NSData alloc] init];
imageDataPicker = UIImageJPEGRepresentation(pickerImage, 0.1); //For resize
if([imageDataPicker length]<2097152) //bytes 1048576
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
[self dismissViewControllerAnimated:YES completion:nil];
picker=nil;
[self SubmitImage1:pickerImage];
}
-(void)SubmitImage1:(UIImage *)image
{
EditProfileImage.image=image; //insert image into imageview
//Create circle imageview
EditProfileImage.layer.cornerRadius = EditProfileImage.frame.size.width / 2;
[EditProfileImage setContentMode:UIViewContentModeScaleAspectFit];
EditProfileImage.layer.masksToBounds = YES;
EditProfileImage.layer.borderWidth = 3.0f;
EditProfileImage.layer.borderColor = [UIColor blackColor].CGColor;
}
enter image description here
enter image description here

Removed a few unnecessary lines and changed the image view to do aspect fill of the resulting image. I have tested this and it works fine with whatever images I tried.
-(IBAction)buttonPressed:(UIButton *)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)Info
{
NSData *imageDataPicker = UIImageJPEGRepresentation(image, 0.1); //For resize
if([imageDataPicker length]<2097152) //bytes 1048576
{
[self dismissViewControllerAnimated:YES completion:nil];
[self SubmitImage1:image];
}
}
// UIViewContentModeScaleAspectFill will fill the entire view
-(void)SubmitImage1:(UIImage *)image
{
_EditProfileImage.image = image;
_EditProfileImage.layer.cornerRadius = _EditProfileImage.frame.size.width / 2;
_EditProfileImage.contentMode = UIViewContentModeScaleAspectFill;
_EditProfileImage.layer.masksToBounds = YES;
_EditProfileImage.layer.borderWidth = 3.0f;
_EditProfileImage.layer.borderColor = [UIColor blackColor].CGColor;
}

Related

How to optimize UITextView

I use UITextView as the rich text view
- (void)openPhotoLibrary {
[self presentImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)presentImagePickerController:(UIImagePickerControllerSourceType)sourceType {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = sourceType;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataImage = UIImageJPEGRepresentation(image, 0.1);
UIImage *resultImage = [UIImage imageWithData:dataImage];
[self insertImageOfTheTextView:self.textview withImage:resultImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)insertImageOfTheTextView:(UITextView *)textView withImage:(UIImage *)image {
if (image == nil || ![image isKindOfClass:[UIImage class]]) {
return;
}
NImageAttachment *attachment = [[NImageAttachment alloc] init];
attachment.image = image;
attachment.imageSize = [self scaleImageSize:image];
NSAttributedString *imageAttributedString = [self insertImageDoneAutoReturn:[NSAttributedString attributedStringWithAttachment:attachment]];
[textView.textStorage insertAttributedString:imageAttributedString atIndex:textView.selectedRange.location];
textView.selectedRange = NSMakeRange(textView.selectedRange.location + 3, 0);
}
- (CGSize)scaleImageSize:(UIImage *)image {
CGFloat imageScale = image.size.width / image.size.height;
CGFloat imageWidth = self.view.frame.size.width;
CGSize imageSize = CGSizeMake(imageWidth, imageWidth / imageScale);
return imageSize;
}
- (NSAttributedString *)insertImageDoneAutoReturn:(NSAttributedString *)imageAttributedString {
NSAttributedString *returnAttributedString = [[NSAttributedString alloc] initWithString:#"\n"];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttributedString];
[attributedString appendAttributedString:returnAttributedString];
[attributedString insertAttributedString:returnAttributedString atIndex:0];
return attributedString;
}
If the photo I picked from PhotoLibrary is small, the uitextivew will be fine, if the photo is large, the uitextview will be slow when I scroll or edit the uitextview, it seems stucks, how can I optimize it?

Crop UIImagePicker and output to CollectionView cell

I am trying to create a camera button that takes a square picture that then fills a CollectionViewController cell. Right now, I'm having a little trouble cropping the picture and outputting it to the cell. In the lines of code commented "Crop the image to a square: I'm getting an error saying that "image" is an undeclared identifier. How do I crop the image and set it to a cell?
- (IBAction)cameraButtonClicked:(id)sender {
if (![UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
UIAlertView *cameraAlertView = [[UIAlertView alloc] initWithTitle:#"Camera Not Available" message:#"There is no camera on this device which really defeats the purpose of this game. We suggest you get an iDevice with a camera." delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[cameraAlertView show];
}else{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
if (ipc.sourceType == UIImagePickerControllerSourceTypeCamera) {
//Create camera overlay
CGRect f = ipc.view.bounds;
f.size.height -= ipc.navigationBar.bounds.size.height;
CGFloat barHeight = (f.size.height - f.size.width) / 2;
UIGraphicsBeginImageContext(f.size);
[[UIColor colorWithWhite:0 alpha:.5] set];
UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, barHeight), kCGBlendModeNormal);
UIRectFillUsingBlendMode(CGRectMake(0, f.size.height - barHeight, f.size.width, barHeight), kCGBlendModeNormal);
UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
overlayIV.image = overlayImage;
[ipc.cameraOverlayView addSubview:overlayIV];
}
ipc.delegate = self;
[self presentViewController:ipc animated:YES completion:nil];
//Crop the image to a square
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width != height) {
CGFloat newDimension = MIN(width, height);
CGFloat widthOffset = (width - newDimension) / 2;
CGFloat heightOffset = (height - newDimension) / 2;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.);
[image drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
blendMode:kCGBlendModeCopy
alpha:1.];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
}
#pragma mark ImagePicker Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Move your "Crop" coded below this line:
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; in
didFinishPickingMediaWithInfo
You will need to update your dataSource with the newly cropped image. You can then either call reloadData or insertItemsAtIndexPaths: on your UICollectionView to have it reflect the newly added image. I would side with calling the latter method as it will be more efficient than reloading the entire collection with reloadData (when there are lots of images in the collection).
UICollectionView reference is here.

How to fade BOTH status bar and navigation bar LIKE Photos.app, on iOS 7

Basically, it's a very simple demand, but I've tried several methods and none of them works as expected. The closest functioning snippet is:
#import "ViewController.h"
#implementation ViewController
- (void)dealloc
{
[scrollView release];
scrollView = nil;
[super dealloc];
}
- (id)init
{
if (self = [super init])
{
self.title = #"Pictures";
scrollView = [[UIScrollView alloc] init];
scrollView.delegate = self;
scrollView.frame = CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 10, scrollView.bounds.size.height);
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.pagingEnabled = YES;
scrollView.userInteractionEnabled = YES;
scrollView.backgroundColor = [UIColor blackColor];
self.wantsFullScreenLayout = YES;
self.automaticallyAdjustsScrollViewInsets = NO;
isHidden = NO;
}
return self;
}
- (void)viewDidLoad
{
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tap:)];
[scrollView addGestureRecognizer:tapGesture];
[tapGesture setNumberOfTapsRequired:1];
[tapGesture release];
for (int i = 0; i < 10; i++)
{
UIImage *image = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:#"/path/to/%d.png", i + 1]];
UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width * i, 0.0f, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = image;
[scrollView addSubview:imageView];
[image release];
[imageView release];
}
[self.view addSubview:scrollView];
}
- (void)tap:(UITapGestureRecognizer *)gesture
{
[UINavigationBar setAnimationDuration:1.0];
[UINavigationBar beginAnimations:#"HideTopBars" context:nil];
isHidden = !isHidden;
// [self setNeedsStatusBarAppearanceUpdate];
self.navigationController.navigationBar.alpha = isHidden ? 0.0f : 1.0f;
[UINavigationBar commitAnimations];
}
- (void)scrollViewDidScroll:(UIScrollView *)view
{
// further operation
}
- (BOOL)prefersStatusBarHidden
{
return isHidden;
}
#end
Without "[self setNeedsStatusBarAppearanceUpdate]", navigation bar does fade as expected, but texts on status bar remain visible, which I guess is because status bar takes navigation bar as it's background image and status bar itself doesn't fade; With "[self setNeedsStatusBarAppearanceUpdate]", the texts also fade, but navigation bar's animation becomes sliding in/out from the top of the screen along with fade effect. I've also tried to move "[self setNeedsStatusBarAppearanceUpdate]" into prefersStatusBarHidden, but that just made navigation bar visible forever. I believe this is not an odd demand, so I bet there're better and simpler solutions. Any idea?

Resizing an image in uiimage and saving it with the new size to the photo album

I'm trying to load an image from the photo album in an image view and then hit a button to resize and then another to save the image with the new size.
Evrything is working well except that the image saved has the same size as the original.
this is what I did so far:
- (IBAction)chooseImage:(id)sender
{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:self.imagePicker animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.chosenImage = info[UIImagePickerControllerOriginalImage];
[self.imageView setImage:self.chosenImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)reSize:(id)sender
{
CGRect newFrame = CGRectMake(20, 49, 280, 200);
[UIView animateWithDuration:0.25f
animations:^{
self.imageView.frame = newFrame;
}];
}
- (IBAction)saveImage:(id)sender
{
UIImageWriteToSavedPhotosAlbum(_chosenImage, self, nil, nil);
}
#end
UIImageView* image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"whatever"]];
CGSize size = image.bounds.size;
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform flipVertical = CGAffineTransformMake(
1, 0, 0, -1, 0, size.height
);
CGContextConcatCTM(context, flipVertical);
CGContextDrawImage(context, image.bounds, image.image.CGImage);
UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(resized, self, nil, nil);
Replace image with the resized imageview that you want to draw.
You can reuse this resize code by creating an UIImage category, there's also an existing good UIImage category that can do image resize and few other things an good example of its usage can be found here.

How to display imagepickercontroller through popoverview controller?

I have used the following code to get photos from album in iphone but it displays the error "UIImagePickerController must be presented via UIPopoverController"
- (void)showImagePicker:(UIImagePickerControllerSourceType)sourceType
{
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
[self setupImagePicker:sourceType];
[self presentModalViewController:imagePickerController animated:YES];
}
}
- (void)setupImagePicker:(UIImagePickerControllerSourceType)sourceType
{
imagePickerController.sourceType = sourceType;
if (sourceType == UIImagePickerControllerSourceTypeCamera)
{
// user wants to use the camera interface
//
imagePickerController.showsCameraControls = NO;
if (imagePickerController.cameraOverlayView != self.view)
{
// setup our custom overlay view for the camera
//
// ensure that our custom view's frame fits within the parent frame
CGRect overlayViewFrame = imagePickerController.cameraOverlayView.frame;
CGRect newFrame = CGRectMake(0.0,
CGRectGetHeight(overlayViewFrame) -
self.view.frame.size.height - 9.0,
CGRectGetWidth(overlayViewFrame),
self.view.frame.size.height + 9.0);
self.view.frame = newFrame;
imagePickerController.cameraOverlayView = self.view;
}
}
}
-(IBAction)getPhoto:(id)sender {
imagePickerController = [[UIImagePickerController alloc] init];
[self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}
Can any one please alter my code to work on iPad.
Thanks in advance.
-(IBAction)Click_event
{
UIImagePickerController *imagePickerController_=[[UIImagePickerController alloc] init];
UIPopoverController *popover_=[[UIPopoverController alloc] initWithContentViewController:imagePickerController_];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
imagePickerController_.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[popover_ presentPopoverFromRect:CGRectMake(400, 400, 0, 0) inView:self.Mybutton
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
}