Taking a screnshot of a UIView iOS - ios

I want to take a screenshot of a UIView (the view would contain a signature) and save it to a local file in the application files, so that the image can be called up at a later point to be displayed in something like a UIImageView. Below is the code behind the signature UIView.
#import "NISignatureViewQuartz.h"
#import <QuartzCore/QuartzCore.h>
#implementation NISignatureViewQuartz
UIBezierPath *path;
- (void)commonInit
{
path = [UIBezierPath bezierPath];
// Capture touches
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(pan:)];
pan.maximumNumberOfTouches = pan.minimumNumberOfTouches = 1;
[self addGestureRecognizer:pan];
// Erase with long press
[self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(erase)]];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) [self commonInit];
return self;
}
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) [self commonInit];
return self;
}
- (void)erase
{
path = [UIBezierPath bezierPath];
[self setNeedsDisplay];
}
- (void)pan:(UIPanGestureRecognizer *)pan {
CGPoint currentPoint = [pan locationInView:self];
if (pan.state == UIGestureRecognizerStateBegan) {
[path moveToPoint:currentPoint];
} else if (pan.state == UIGestureRecognizerStateChanged)
[path addLineToPoint:currentPoint];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[[UIColor blackColor] setStroke];
[path stroke];
}
#end
How would I go about doing this?

You want to render the view's layer into a graphics context. It's very straightforward. In your NISignatureViewQuartz class you can add this method:
- (UIImage *)snapshot {
UIGraphicsBeginImageContext(self.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

I wrote an useful helper class, to take and manage screenshot:
#implementation MGImageHelper
/* Get the screenshot of an UIView (so take just UIKit elements and not OpenGL or AVFoundation stuff. */
+ (UIImage *)getScreenshotFromView:(UIView *)captureView
{
CGRect rect = [captureView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[captureView.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return capturedImage;
}
/* Get the screenshot of a determinate rect of an UIView, and scale it to the size that you want. */
+ (UIImage *)getScreenshotFromView:(UIView *)captureView withRect:(CGRect)captureRect andScaleToSize:(CGSize)newSize
{
UIImage *image = [[self class] getScreenshotFromView:captureView];
image = [[self class] cropImage:image withRect:captureRect];
image = [[self class] scaleImage:image toSize:newSize];
return image;
}
/* Get the screenshot of the screen (useful when you have UIKit elements and OpenGL or AVFoundation stuff */
+ (UIImage *)screenshotFromScreen
{
CGImageRef UIGetScreenImage(void);
CGImageRef screen = UIGetScreenImage();
UIImage* screenImage = [UIImage imageWithCGImage:screen];
CGImageRelease(screen);
return screenImage;
}
/* Get the screenshot of a determinate rect of the screen, and scale it to the size that you want. */
+ (UIImage *)getScreenshotFromScreenWithRect:(CGRect)captureRect andScaleToSize:(CGSize)newSize
{
UIImage *image = [[self class] screenshotFromScreen];
image = [[self class] cropImage:image withRect:captureRect];
image = [[self class] scaleImage:image toSize:newSize];
return image;
}
/* Methods used from methods above but also usable in singular */
+ (UIImage *)cropImage:(UIImage *)image withRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *cropedImage = [UIImage imageWithCGImage:imageRef];
return cropedImage;
}
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
#end

You can use UIView method available starting from iOS 7, designed specifically for that:
- (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates;
e.g.
UIGraphicsBeginImageContext(self.bounds.size);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Related

Covert UIVIew to UIImage without presenting/displaying UIView

I am using method to convert UIView to UIImage and its doing a great job when UIView (to be converted to UIImage) is already present/displayed. But my requirement is to convert UIView to UIImage without displaying UIView. Unfortunately, this code is failing in this case and I am stuck. Any help will be appreciated.
I am using the following method:
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Your code is likely failing because you're not laying out the subviews of your view (which is done automatically when you add a view as a subview). Try something like the method I wrote below:
+ (UIImage *)imageFromView:(UIView *)view sized:(CGSize)size
{
// layout the view
view.frame = CGRectMake(0, 0, size.width, size.height);
[view setNeedsLayout];
[view layoutIfNeeded];
// render the image
UIGraphicsBeginImageContextWithOptions(size, view.opaque, 0.0f);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return renderedImage;
}
Assuming you have already got a working view, this code should work to convert the UIView to a UIImage (I'm using it to convert a gradient into an image and display the image onto a UIProgressView.
Swift:
let renderer = UIGraphicsImageRenderer(size: gradientView.bounds.size)
let image = renderer.image { ctx in
gradientView.drawHierarchy(in: gradientView.bounds, afterScreenUpdates: true)
}
Objective C:
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:gradientView.bounds.size];
UIImage *gradientImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
[gradientView drawViewHierarchyInRect:gradientView.bounds afterScreenUpdates:true];
}];
_progressView.progressImage = gradientImage;
The above code should allow you to convert any UIView to a UIImage. You should ideally be running it in the viewWillAppear (as at this point the view controller will have the correct layout sizes). If you have any problems getting this to work you can have a look at these example projects that I made for a guide on this very topic! Objective C, Swift.
Hide all subviews, and then snapshot UIview to UIImage should work, see code below
+ (UIImage *)custom_snapshotScreenInView:(UIView *)contentView
{
if (!contentView) {
return nil;
}
CGSize size = contentView.bounds.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGRect rect = contentView.bounds;
[contentView drawViewHierarchyInRect:rect afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
return image;
}
+ (UIImage *)custom_snapshotScreenWithoutSubviews:(UIView *)contentView
{
// save hidden view's hash
NSMutableArray *hideViewsHashs = [[NSMutableArray alloc]initWithCapacity:contentView.subviews.count];
for (UIView *subview in contentView.subviews) {
if (subview.hidden == NO) {
[hideViewsHashs addObject:#(subview.hash)];
NSLog(#"Dikey:video:snap:hash = %#", #(subview.hash));
}
subview.hidden = YES;
}
// view to image
UIImage *image = [UIImage custom_snapshotScreenInView:contentView];
// restore
for (UIView *subview in contentView.subviews) {
if ([hideViewsHashs containsObject:#(subview.hash)]) {
subview.hidden = NO;
NSLog(#"Dikey:video:snap:restore:hash = %#", #(subview.hash));
}
}
// finish
return image;
}

iOS imageview crop not working when work with device photos

I have planed to create a image edit application. first step i gonna show touched position of image in to a separate image view from original image view.
Its's working fine when test with default image(which one is set from xcode storyboard attribute inspector).
But its not crop a exact image when i import a photo from device "Photos".
I am really confused and stuck on there. please some one guide me to do this task.
I have try with the Below code
Thanks in advance.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
imgVw.image = image;
// croperImgvw.image = [self cropImage : image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (UIImage *)cropImage:(UIImage *)image : (CGPoint)point
{
CGRect clippedRect =CGRectMake(point.x, point.y, 50, 50);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
UIImage * croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touch_point = [touch locationInView:self.view];
NSLog(#"X location: %f", touch_point.x);
NSLog(#"Y Location: %f",touch_point.y);
CGPoint point = [touch locationInView:self.view];
croperImgvw.image = [self cropImage:[imgVw image] :point];
}
As I understand, your point parameter that you are passing to cropImage:image: method are from UIImageView coordinate system - and rect parameter in CGImageCreateWithImageInRect must be taken from UIImage, not from UIImageView.
Here is couple answers of how you can solve this problem:
https://stackoverflow.com/a/10865552/4495995
https://stackoverflow.com/a/21693491/4495995
It looks like you're passing a coordinate from a view in order to crop to an image. An image view and its image will rarely have the same dimensions, especially if you're picking images from Photos.
Try rendering the first view into an image before sending that image to be cropped. You can do this by adding a category to UIView like this:
#implementation UIView (Image)
- (UIImage *)image {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#end
Edit: Or if you just want to get it working without categories, add this method to your code:
- (UIImage *)imageOfView:(UIImageView *)imageView {
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 0.0);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Then modify your existing code to read:
croperImgvw.image = [self cropImage:[self imageOfView:imgVw] :point];
Addition to norder's answer It's good to add scale parameter because of the different resolutions.
TakeSnapshot.h
#import <Foundation/Foundation.h>
#interface TakeSnapshot : NSObject
+(UIImage *)takeSnapshotFromScreenWithSize:(UIView *)view Area:(CGPoint)screenPoint;
#end
TakeSnapshot.m
#import "TakeSnapshot.h"
#implementation TakeSnapshot
+(UIImage *)takeSnapshotFromScreenWithSize:(UIView *)view Area:(CGPoint)screenPoint{
{
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]){
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
}
else
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//
if([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.bounds.size.width, view.bounds.size.width),NO,[UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(view.bounds.size);
[screenImage drawAtPoint:screenPoint];
UIImage *shareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return shareImage;
}
}
#end

Capture iPhone screen

I am using following code to capture screen. Before it was working fine but now its retuning nil image.I am using iPhone 5,5c and 5s.
+ (UIImage *)screenshot
{
CGSize imageSize = CGSizeZero;
imageSize = [UIScreen mainScreen].bounds.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
CGContextSaveGState(context);
CGContextTranslateCTM(context, window.center.x, window.center.y);
CGContextConcatCTM(context, window.transform);
CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
if ([window respondsToSelector:#selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
}
else
{
[window.layer renderInContext:context];
}
CGContextRestoreGState(context);
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Now I am using this code and its working good.
+ (UIImage *)screenshot:(UIView *)view
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);
[view.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Here is a method that I use to capture a UIView into a UIImage.
+ (UIImage *)renderView:(UIView *)view toImageWithSize:(CGSize)size {
UIGraphicsBeginImageContextWithOptions(size, NO, 0.);
CGContextRef c = UIGraphicsGetCurrentContext();
[view.layer renderInContext:c];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
And then you can have your screenshot method that uses the method above to render the rootViewController of the main window into an image:
+ (UIImage *)screenshot {
UIWindow *mainWindow = [UIApplication sharedApplication].windows.firstObject;
UIView *mainView = mainWindow.rootViewController.view;
return [self renderView:mainView toImageWithSize:mainView.bounds.size];
}
I hope this is helpful.
Well, this piece of code works for me. This code capture a screenshot of the view (self.view here) and all its subviews. Means, in one word, screenshot of the screen.
+ (UIImage *)screenshot {
CGRectMake *captureFrame = [[UIScreen mainScreen] bounds]; //The portion and size of the area, you want to capture. I have set it to the size of window
CALayer *layer;
layer = self.view.layer;
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenImage;
}
Hope this helps.

Cropping an Image to the shape of an Overlay - iOS

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");
}
}

How to take screenshot of expandable uitableview programmatically

I tried to take screenshot of expandable uitableview, I tried to take a screenshot of uitableview but I was not able do that , then I changed tableview frame size to tableview content size. After taking screenshot I changed frame size to old frame size. Now the problem is that I am having expandable section in table view. I'm able to take screenshot of unexpanded table view cell in my screenshot. I need to take the screenshot of unexpanded table view cell content too.
by using this category file u can take the screen shot what ever visible in the screen....
#interface UIImage (MyImage)
+ (UIImage*)imageFromView:(UIView*)view;
+ (UIImage*)imageFromView:(UIView*)view scaledToSize:(CGSize)newSize;
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
+ (void)beginImageContextWithSize:(CGSize)size;
+ (UIImage *)croppedImage:(UIImage *)myImage :(CGRect)bounds;
#end
#import "UIImage+MyImage.h"
#implementation UIImage (MyImage)
+ (void)beginImageContextWithSize:(CGSize)size
{
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
UIGraphicsBeginImageContextWithOptions(size, YES, 2.0);
} else {
UIGraphicsBeginImageContext(size);
}
} else {
UIGraphicsBeginImageContext(size);
}
}
+ (void)endImageContext
{
UIGraphicsEndImageContext();
}
+ (UIImage*)imageFromView:(UIView*)view
{
[self beginImageContextWithSize:[view bounds].size];
BOOL hidden = [view isHidden];
[view setHidden:NO];
[[view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
[self endImageContext];
[view setHidden:hidden];
return image;
}
+ (UIImage*)imageFromView:(UIView*)view scaledToSize:(CGSize)newSize
{
UIImage *image = [self imageFromView:view];
if ([view bounds].size.width != newSize.width ||
[view bounds].size.height != newSize.height) {
image = [self imageWithImage:image scaledToSize:newSize];
}
return image;
}
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
[self beginImageContextWithSize:newSize];
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
[self endImageContext];
return newImage;
}
+ (UIImage *)croppedImage:(UIImage *)myImage :(CGRect)bounds {
CGImageRef imageRef = CGImageCreateWithImageInRect(myImage.CGImage, bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGSize asd = croppedImage.size;
return croppedImage;
}
#end
the method call will be....
yourImageView.image= [UIImage imageFromView:(UIView*)yourTableViewInstance ]
try this....

Resources