I'm adding the overlay using pickerController's view and the uinavigationcontrollerdelegate as below.
-(void)navigationController:(UINavigationController *)navigationController didShowViewController: (UIViewController *)viewController animated:(BOOL)animated{
if ([navigationController.viewControllers count] == 3)
{
CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
UIView *plCropOverlay = [[[viewController.view.subviews objectAtIndex:1]subviews] objectAtIndex:0];
plCropOverlay.hidden = YES;
int position = 0;
if (screenHeight == 568)
{
position = 124;
}
else
{
position = 80;
}
CAShapeLayer *circleLayer = [CAShapeLayer layer];
UIBezierPath *path2 = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0.0f, position, 320.0f, 320.0f)];
[path2 setUsesEvenOddFillRule:YES];
[circleLayer setPath:[path2 CGPath]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 320, screenHeight-72) cornerRadius:0];
[path appendPath:path2];
[path setUsesEvenOddFillRule:YES];
CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor blackColor].CGColor;
fillLayer.opacity = 0.8;
[viewController.view.layer addSublayer:fillLayer];
}
}
When the overlay defined above is added, I tend to get this view:
I can crop the image exactly to a square using a defined CGRect.
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
How about approaching this problem where there is a circular overlay and imagePickers editing property is YES? I can zoom in and zoom out of the pic. How can i make use of the BezierPath here?
the short answer to your question addClip , but you mention you're a beginner, so here's all the steps from A to Z!!
Firstly, try this category, see if it helps. (If you're not familiar w/ categories have a google or just ask here in a comment.)
-(UIImage *)doMask
{
UIImage *maskImage = [UIImage imageNamed:#"yourMask.png"];
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef maskedImageRef = CGImageCreateWithMask([self CGImage], mask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(mask);
CGImageRelease(maskedImageRef);
return maskedImage;
}
just create (I mean in photoshop) a png mask, and get familiar with that process.
I encourage you to master that process first...
Here are critical categories that will help...
-(UIImage *)becomeSquare
{
CGSize imageSize = self.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
UIImage *result = self;
if (width != height)
{
CGFloat newDimension = MIN(width, height);
CGFloat widthOffset = (width - newDimension) / 2;
CGFloat heightOffset = (height - newDimension) / 2;
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(newDimension, newDimension), NO, 0. );
[result drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
blendMode:kCGBlendModeCopy alpha:1. ];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return result;
}
and a couple more ...
-(UIImage *)doScale
{
UIImage *result = self;
CGSize size = CGSizeMake(320,320);
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[result drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
-(UIImage *)scaled640AnyShape
{
if ( self.size.height < 5.0 ) return nil;
if ( self.size.width < 5.0 ) return nil;
UIImage *result = self;
float widthShouldBe = 640.0;
float heightShouldBe = widthShouldBe * ( self.size.height / self.size.width );
CGSize size = CGSizeMake( widthShouldBe ,heightShouldBe );
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[result drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
(obviously change the hard-coded output sizes as you wish.)
Note that your final result, will be achieved, by a combination in the appropriate order, such as:
yourImage = [yourImage doSquare];
yourImage = [yourImage doMask];
once you've got that working ...
Then ....
for LITERALLY what you ask, there are many example codes about .. e.g., what about https://stackoverflow.com/a/13870097/294884
As you can see, you fundamentally...
UIGraphicsBeginImageContextWithOptions(...);
UIBezierPath * path = [UIBezierPath
bezierPathWithRoundedRect:imageRect cornerRadius:10.f];
[path addClip];
[yourImage drawInRect:imageRect];
... then ... UIGraphicsGetImageFromCurrentImageContext();
.. see the extensive code above for how to save it and so on.
You just have to get the zoom right with the scaling examples above.
Also note this, when you are changing the "area cropped"... https://stackoverflow.com/a/17884863/294884
here's an example of that critical technique...
-(UIImage *)squareAndSmall
{
// genius credits: https://stackoverflow.com/a/17884863/294884
CGSize finalsize = CGSizeMake(640,640);
CGFloat scale = MAX(
finalsize.width/self.size.width,
finalsize.height/self.size.height);
CGFloat width = self.size.width * scale;
CGFloat height = self.size.height * scale;
// for example, the central area....
CGRect imageRect = CGRectMake(
(finalsize.width - width)/2.0f,
(finalsize.height - height)/2.0f,
width, height);
// or, the top area... CGRect imageRect = CGRectMake( 0, 0, width, height);
UIGraphicsBeginImageContextWithOptions(finalsize, NO, 0);
[self drawInRect:imageRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Hope it all helps!
Found this blog post entry very interesting, neat and simple to follow by Nimit Parekh.
Following code is copy/paste into your “viewcontroller.h” file:
#import <UIKit/UIKit.h>
#interface UIImagePickerDemoViewController : UIViewController< UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property(nonatomic,retain) UIImagePickerController *imgPicker;
#property(nonatomic,retain) IBOutlet UIImageView *image_view;
//- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect;
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage;
#end
Following Code copy/paste into “viewcontroller.m” file:
// Following method is use for the mask the image.
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
// Following method is use for Cropping the image for a perticular size.
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0.0, rect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);
CGRect drawRect = CGRectMake(rect.origin.x * -1,rect.origin.y * -1,imageToCrop.size.width,imageToCrop.size.height);
CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
CGContextScaleCTM(currentContext, 1.0, -1.0);
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cropped;
}
// Calling the method of maskimage.
//=============================Camera Enable(display)============================================
-(IBAction)next:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:self.imgPicker animated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *img = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
self.image_view.image=[self maskImage:img withMask:[UIImage imageNamed:#"frame.png"]];
}
//===============================================================================================
// Calling the method of cropping the image.
//=============================Camera Enable(display)============================================
-(IBAction)next:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:self.imgPicker animated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *img = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
self.image_view.image = [self imageByCropping:img toRect:CGRectMake(0, 0, 420, 40)];
}
//===============================================================================================
Output:
Grab the source code here.
Im having exactly the same profile image picker controller as your. Here is my code from delegate. I don't think you need everything but you can find some useful information here
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString *) kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
UIImage *editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
CGRect croppingRect = [info[UIImagePickerControllerCropRect] CGRectValue];
if (editedImage) {
image = editedImage;
} else {
CGFloat smaller = 1;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
smaller = 0.9;
}
CGFloat width = MIN(image.size.width * smaller, image.size.height * (smaller * 0.95));
croppingRect = CGRectMake(0 + (image.size.width - width) / 2,
0 + (image.size.height - width) / 2,
width, width);
}
UIImage *finalImage = nil;
if (editedImage) {
finalImage = [UIImage image:editedImage byScalingAndCroppingForSize:kCroppedImageSize];
} else {
finalImage = [UIImage image:image byScalingAndCroppingForSize:kCroppedImageSize];
}
if ([self.imagePickerDelegate respondsToSelector:#selector(profileImagePicker:didSelectImage:)]) {
[self.imagePickerDelegate profileImagePicker:self didSelectImage:finalImage];
} else {
NSAssert(nil, #"Delegate should confirm ProfileImagePickerControllerDelegate protocol");
}
} else if ([mediaType isEqualToString:(NSString *) kUTTypeVideo]) {
NSAssert(nil, #"Movie is not supported");
}
}
Related
Hi I am developing an iOS app. I have an UIImageView with a image associated with it. I am changing its dimensions in viewDidLoad() method.
Initially when I change the dimension I am able to resize the image size on view. However after I crop the image(using Photoshop) accordingly to the shape of the object in the image(i.e getting rid of unwanted part of the image). My resize method doesn't seem to work i.e the size of the image is not changing though I call the same method.
The method I am using for resizing is given below.
-(void)initXYZ{
CGSize size;
CGFloat x,y;
x = 0+myImageView1.frame.size.width;
y = myImageView2.center.y;
size.width = _myImageView2.frame.size.width/2;
size.height = _myImageView2.frame.size.width/2;
UIImage *image = [UIImage imageNamed:#"xyz.png"];
image = [HomeViewController imageWithImage:image scaledToSize:size xCord:x yCord:y];}
Utility method is given below
+(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize xCord:(CGFloat)X yCord:(CGFloat)Y{
UIGraphicsBeginImageContextWithOptions(newSize,NO,0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}
Try this...
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
OR
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipV = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipV);
CGContextDrawImage(context, newRect, imageRef);
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
Try this:
- (UIImage*)resizeAndStoreImages:(UIImage*)img
{
UIImage *chosenImage = img;
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1.0);
int resizedImgMaxHeight = 500;
int resizedImgMaxWidth = 500;
UIImage *resizedImageData;
if (chosenImage.size.height > chosenImage.size.width && chosenImage.size.height > resizedImgMaxHeight) { // portrait
int width = (chosenImage.size.width / chosenImage.size.height) * resizedImgMaxHeight;
CGRect rect = CGRectMake( 0, 0, width, resizedImgMaxHeight);
UIGraphicsBeginImageContext(rect.size);
[chosenImage drawInRect:rect];
UIImage *pic1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
resizedImageData = [UIImage imageWithData:UIImageJPEGRepresentation(pic1, 1.0)];
pic1 = nil;
} else if (chosenImage.size.width > chosenImage.size.height && chosenImage.size.width > resizedImgMaxWidth) { // landscape
int height = (chosenImage.size.height / chosenImage.size.width) * resizedImgMaxWidth;
CGRect rect = CGRectMake( 0, 0, resizedImgMaxWidth, height);
UIGraphicsBeginImageContext(rect.size);
[chosenImage drawInRect:rect];
UIImage *pic1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
resizedImageData = [UIImage imageWithData:UIImageJPEGRepresentation(pic1, 1.0)];
pic1 = nil;
} else {
if (chosenImage.size.height > resizedImgMaxHeight) {
int width = (chosenImage.size.width / chosenImage.size.height) * resizedImgMaxHeight;
CGRect rect = CGRectMake( 0, 0, width, resizedImgMaxHeight);
UIGraphicsBeginImageContext(rect.size);
[chosenImage drawInRect:rect];
UIImage *pic1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
resizedImageData = [UIImage imageWithData:UIImageJPEGRepresentation(pic1, 1.0)];
pic1 = nil;
} else {
resizedImageData = [UIImage imageWithData:imageData];
}
}
return resizedImageData;
}
Adjust the resizedImgMaxHeight and resizedImgMaxWidth as per your need
I'm using UIImagePickerController to choose an image from my Camera Roll and resizing it before uploading it to Parse.
I want to resize an image to certain size (let's say 750x1000) while retaining the aspect ratio of the original image. If necessary, I want to crop the image. I also want it to be easy to have different versions of the image (full size, thumbnail size). Right now I'm resizing only the height of the image. How can I achieve what I'm looking for?
Thanks.
NewProductViewController.h
#interface NewProductViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>
#property (nonatomic, strong) UIImage *image;
#property (nonatomic, strong) UIImagePickerController *imagePicker;
#property (nonatomic, weak) IBOutlet UIImageView *imageView;
- (UIImage *)imageWithImage:(UIImage *)sourceImage scaledToHeight:(float) i_height;
#end
NewProductViewController.m
- (IBAction)addImage:(id)sender {
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePicker.delegate = self;
self.imagePicker.allowsEditing = NO;
[self presentViewController:self.imagePicker animated:NO completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was selected
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
[self.imageView setImage:self.image];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage *)imageWithImage:(UIImage *)sourceImage scaledToHeight:(float) i_height {
float oldHeight = sourceImage.size.height;
float scaleFactor = i_height / oldHeight;
float newWidth = sourceImage.size.width* scaleFactor;
float newHeight = oldHeight * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (IBAction)createProduct:(id)sender {
PFObject *newProduct = [PFObject objectWithClassName:#"Product"];
UIImage *newImage = [self imageWithImage:self.image scaledToHeight:1000.f];
UIImage *thumbnailImage = [self imageWithImage:self.image scaledToHeight:410.f];
NSData *imageData = UIImageJPEGRepresentation(newImage, 0.8f);
NSData *thumbnailData = UIImageJPEGRepresentation(thumbnailImage, 0.8f);
PFFile *imageFile = [PFFile fileWithName:#"image.jpg" data:imageData];
PFFile *thumbnailFile = [PFFile fileWithName:#"thumbnail.jpg" data:thumbnailData];
newProduct[#"imageFile"] = imageFile;
newProduct[#"thumbnailFile"] = thumbnailFile;
[newProduct setObject:[PFUser currentUser] forKey:#"user"];
}
Try this one, it crops source image proportionally and then scales it to necessary size:
- (UIImage *)imageWithImage:(UIImage *)sourceImage size:(CGSize)size {
CGSize newSize = CGSizeZero;
if ((sourceImage.size.width / size.width) < (sourceImage.size.height / size.height)) {
newSize = CGSizeMake(sourceImage.size.width, size.height * (sourceImage.size.width / size.width));
} else {
newSize = CGSizeMake(size.width * (sourceImage.size.height / size.height), sourceImage.size.height);
}
CGRect cropRect = CGRectZero;
cropRect.origin.x = (sourceImage.size.width - newSize.width) / 2.0f;
cropRect.origin.y = (sourceImage.size.height - newSize.height) / 2.0f;
cropRect.size = newSize;
CGImageRef croppedImageRef = CGImageCreateWithImageInRect([sourceImage CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:croppedImageRef];
CGImageRelease(croppedImageRef);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, 0.0);
[croppedImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
This code can help you:
UIImage *originalImage = [UIImage imageNamed:#"minions.png"];
CGSize destination = CGSizeMake(750, 1000);
UIGraphicsBeginImageContext(destination);
[originalImage drawInRect:CGRectMake(0,0,destination.width,destination.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *new = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 750, 1000)];
new.image = newImage;
[self.view addSubview:New];
Let me know if it works for you :)
When scaling to precise width or height you may lose image resolution. So my solution is to crop to aspect ratio:
Swift 3
func cropImage(image: UIImage, to aspectRatio: CGFloat) -> UIImage {
let imageAspectRatio = image.size.height/image.size.width
var newSize = image.size
if imageAspectRatio > aspectRatio {
newSize.height = image.size.width * aspectRatio
} else if imageAspectRatio < aspectRatio {
newSize.width = image.size.height / aspectRatio
} else {
return image
}
let center = CGPoint(x: image.size.width/2, y: image.size.height/2)
let origin = CGPoint(x: center.x - newSize.width/2, y: center.y - newSize.height/2)
let cgCroppedImage = image.cgImage!.cropping(to: CGRect(origin: origin, size: CGSize(width: newSize.width, height: newSize.height)))!
let croppedImage = UIImage(cgImage: cgCroppedImage, scale: image.scale, orientation: image.imageOrientation)
return croppedImage
}
This is a simple method I created
-(UIImage *)getRescaledImage:(UIImage *)image{
int height = image.size.height;
int width = image.size.width;
int max = MOImageMaxHeightWidth;
float divideFactor = 0;
if(!(height > max) || !(width > max)){
return image;
}
if(height > width){
divideFactor = height/max;
}else{
divideFactor = width/max;
}
height = height/divideFactor;
width = width/divideFactor;
return [self imageWithImage:image scaledToSize:CGSizeMake(width, height)];
}
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
MOImageMaxHeightWidth is a constant float value which you can give define for the max width/height. The aspect ratio of the image will be maintained. The variable divideFactor will take care of it and is self explanatory.
I have used below UIImage Categories. Hope this will work for you too.
https://github.com/mbcharbonneau/UIImage-Categories
CGFloat scale = .5f;
CGFloat maxSize = 1632 * 1224;
CGFloat currentSize = croppedImage.size.width * croppedImage.size.height;
if ((currentSize / 2) > maxSize) {
scale = maxSize / currentSize;
}
CGSize size = CGSizeMake(croppedImage.size.width * scale, croppedImage.size.height * scale);
__block UIImage *imageToSave = [croppedImage resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:size interpolationQuality:kCGInterpolationLow];
I am implementing below code cropping image to square
- (void)imagePickerController:(UIImagePickerController *)picker1 didFinishPickingMediaWithInfo:(NSDictionary *)info {
tatooImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageView *imageView = [[UIImageView alloc] initWithImage:tatooImage];
CGSize size = [tatooImage size];
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2));
self.imageOverlay.image = [self croppedImage:tatooImage cropRect:rect];
}
- (UIImage *)croppedImage:(UIImage *)image cropRect:(CGRect)cropRect
{
CGImageRef croppedCGImage = CGImageCreateWithImageInRect(image.CGImage, cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:croppedCGImage scale:1.0f orientation:image.imageOrientation];
CGImageRelease(croppedCGImage);
return [croppedImage fixOrientation];
}
Problem i am facing is that i am not getting center part of the image
I am trying to add image to cell, it works, but the scaling is not really working, the image is scaled to some size, and stay in that size, numbers i enter to the scale function don't change a thing .(image is auto scale to some constant size)
NSURL *url = [NSURL URLWithString:icon];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *logo=[UIImage imageWithData:data scale:4];
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 10.0;
cell.imageView.image=logo;
Implement this method and use it:
/*! Returns a UIImage which is resized image of the image provided.
#param image
The image to be resized.
#param size
The size of the image to be resized.
*/
+ (UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size {
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat requiredWidth = (imageWidth * size.height) / imageHeight;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(requiredWidth, size.height), NO, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(0, 0, requiredWidth, size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
return newImage;
}
Just write your masking function inside the custom cell class method declared as below.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
[self.imageView.layer setCornerRadius:10.0];
self.imageView.layer.masksToBounds = YES;
}
Use this function to scale the images as per your requirement.
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
float theScaleFactor = 0.0f;
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
theScaleFactor = 2.0f;
} else {
theScaleFactor = 0.0f;
}
} else {
theScaleFactor = 0.0f;
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, theScaleFactor);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Hope this will help you.
I'm trying to generate an image that is lozenge-shaped and shows some percentage finished versus unfinished. The way I implemented this was as follows:
Generate 2 rectangles - one the size of the filled region, the other the size of the empty rectange
Invoke UIGrapicsBeginImageContext() with the size of the rectangle I am interested in
Draw the 2 rectangles in the context side-by side
Grab the image from the context and end the context
Create a new masked image by using CGImageMaskCreate() followed by CGImageCreateWithMask() and extracting the masked image
I generate the filled and empty bitmaps using category extensions to UIImage, and then apply a static mask image to them.
The Problem: This works fine in the simulator, but the masking doesn't work on a real device.
Instead of including the code here, I'm including a link to a project that has the code. The relevant files are:
UIImage.h/UIImage.m: The category extension to UIImage that adds both the "create an image with a specified color" and "create a masked image using the supplied mask".
TLRangeDisplay.h/TLRangeDisplay.m: the code for my lozenge-shaped status display. The routine of interest there is fillWithRect().
Here is the code I added to UIImage (via a category):
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
CGRect rect = CGRectMake(0.0f, 0.0f, size.height, size.width);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage*) maskWith:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([self CGImage], mask);
UIImage* image = [UIImage imageWithCGImage:masked];
CFRelease(mask);
CFRelease(masked);
return image;
}
And here is the routine that does the masking:
-(void)fillWithRect {
CGRect f = self.frame;
CGFloat width = f.size.width;
CGFloat fullRange = maxValue_ - minValue_;
CGFloat filledRange = currentValue_ - minValue_;
CGRect fillRect = CGRectMake(0, 0, (filledRange * width) / fullRange, f.size.height);
CGRect emptyRect = CGRectMake(fillRect.size.width, 0, width - fillRect.size.width, f.size.height);
UIImage *fillImage = nil;
UIImage *emptyImage = nil;
if(fillRect.size.width > 0) {
fillImage = [UIImage imageWithColor:fillColor_ andSize:fillRect.size];
}
if(emptyRect.size.width > 0) {
emptyImage = [UIImage imageWithColor:emptyColor_ andSize:emptyRect.size];
}
// Build the 2-color image
UIGraphicsBeginImageContext(f.size);
[fillImage drawInRect:fillRect];
[emptyImage drawInRect:emptyRect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Mask it
if(nil != maskImage_)
image = [image maskWith:maskImage_];
CGRect fullRect = CGRectMake(0, 0, f.size.width, f.size.height);
// Merge ith with the shape
UIGraphicsBeginImageContext(f.size);
[image drawInRect:fullRect];
[shapeImage_ drawInRect:fullRect];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[shownView_ removeFromSuperview];
shownView_ = [[UIImageView alloc] initWithImage:image];
[self addSubview:shownView_];
if(nil != shownView_)
[self bringSubviewToFront:shownView_];
}
The project can be downloaded from http://dl.dropbox.com/u/5375467/ColorPlayOS4.zip
Thanks for any insights on this problem!