Sometimes requirement arises in iPhone/iPad app that how we get screenshot of a particular UI part. So this captured screenshot can be sent as attachment to authorities via mail or can be written on to photo library.
MyImage Subclass of UIImage
We have to make subclass of UIImage that is MyImage and we are going to implement some extra methods inside it to get screen shot of a particular UI part. so customized MyImage Class code is given below.
MyImage.h File
@interface UIImage (MyImage)
+ (UIImage*)imageFromView:(UIView*)view;
+ (UIImage*)imageFromView:(UIView*)view scaledToSize:(CGSize)newSize;
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
@end
MyImage.m File
#import < QuartzCore/QuartzCore.h>
#import "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;
}
@end
TakeScreenShot Method
This is method, put inside your class where-ever you need to take screenshot Here
1) filePath is Document Directory path where your screenshot will be stored finally.
2) customizedView is your View , whose screenshot you want to capture.
-(void)takeScreenShot{
NSArray *arrPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *strDocumentPath = [arrPaths objectAtIndex:0];
NSString *filePath = [strDocumentPath stringByAppendingPathComponent:@"screenshot.png"];
UIImage *img = [UIImage imageFromView:customizedView];
//imgSignature.image = img;
NSData *imgData = UIImageJPEGRepresentation(img, 0.0);
[imgData writeToFile:filePath atomically:YES];
}
0 comments:
Post a Comment