I need share Screenshot of my app in Facebook (I use Cocos2D 3.0), but the code not function:
// For take Screenshot of App
-(UIImage *)capture
{
AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
// for retina-display
UIGraphicsBeginImageContextWithOptions(_appDelegate.window.bounds.size, NO, [UIScreen mainScreen].scale);
[_appDelegate.window drawViewHierarchyInRect:_appDelegate.window.bounds afterScreenUpdates:NO];
} else {
// non-retina-display
UIGraphicsBeginImageContext(_appDelegate.window.bounds.size);
[_appDelegate.window drawViewHierarchyInRect:_appDelegate.window.bounds afterScreenUpdates:NO];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
-(void)btnSharedFacebookTapped:(id)sender
{
[self capture];
FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
photo.image = [self capture];
// photo.userGenerated = YES;
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = #[photo];
[FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
}
-(UIImage*) takeGameScreenshot
{
[CCDirector sharedDirector].nextDeltaTimeZero = YES;
CGSize size = [[CCDirector sharedDirector] viewSize];
CCRenderTexture *renderTxture = [CCRenderTexture renderTextureWithWidth:size.width
height:size.height];
[renderTxture begin];
[[[CCDirector sharedDirector] runningScene] visit];
[renderTxture end];
return [renderTxture getUIImage];
}
-(void)facebookShare:(UIImage*)inImage
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
NSString *textShare;
textShare = [NSString stringWithFormat:#"Checkout ultimate iPhone game %# - %#", GAME_NAME, GAME_SHORT_LINK];
[controller setInitialText:textShare];
[controller addImage:inImage];
[self.navController presentViewController:controller animated:YES completion:nil];
}
-(void)shareImage
{
UIImage *resultImage = [self takeGameScreenshot];
[self facebookShare:mResultImage];
}
Related
I have done zooming functionality in camera with GPUImage. But when I capture image from camera with zoom and save it but still it save as normal pict(no zooming found). I want in whichever mode I capture image that must be saved in album. How can I solve this problem Any suggestion will be great. Thanks guys. My code :
- (void)viewDidLoad {
[super viewDidLoad];
self.library = [[ALAssetsLibrary alloc] init];
[self setViewLayOut];
[self setupFilter];
[self setZoomFunctionlityOnCamera];
}
- (void)setupFilter;
{
videoCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
switch (filterType)
{
case GPUIMAGE_COLORINVERT:
{
self.title = #"Color Negative";
filter = [[GPUImageColorInvertFilter alloc] init];
};
break;
case GPUIMAGE_GRAYSCALE:
{
self.title = #"Black and White Positive";
filter = [[GPUImageGrayscaleFilter alloc] init];
};
break;
default: filter = [[GPUImageFilter alloc] init];
self.title = #"Color Positive";
break;
}
videoCamera.runBenchmark = YES;
filterView = (GPUImageView *)cameraView;
[filter addTarget:filterView];
[videoCamera addTarget:filter];
[videoCamera startCameraCapture];
}
- (IBAction)clickPhotoBtn:(id)sender {
if (!isCameraPermissionAccessed) {
[self showAccessDeinedMessage :#"Camera permission denied" withMessage:#"To enable, please go to settings and allow camera permission for this app."];
return;
}
[videoCamera capturePhotoAsJPEGProcessedUpToFilter:filter withCompletionHandler:^(NSData *processedJPEG, NSError *error){
if (error!=nil)
{
[self showErrorMessage:#"Unable to capture image" ];
return ;
}
else {
UIImage *image = [UIImage imageWithData:processedJPEG];
if (filterType == GPUIMAGE_GRAYSCALE) {
GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:image];
GPUImageColorInvertFilter *stillImageFilter = [[GPUImageColorInvertFilter alloc] init];
[stillImageSource addTarget:stillImageFilter];
[stillImageFilter useNextFrameForImageCapture];
[stillImageSource processImage];
UIImage *currentFilteredVideoFrame = [stillImageFilter imageFromCurrentFramebuffer];
UIImageWriteToSavedPhotosAlbum(currentFilteredVideoFrame, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
else{
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
}
}];
}
Use below code it may helpful to you
+(UIImage*)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom
{
CGFloat zoomReciprocal = 1.0f / zoom;
CGPoint offset = CGPointMake(image.size.width * ((1.0f - zoomReciprocal) / 2.0f), image.size.height * ((1.0f - zoomReciprocal) / 2.0f));
CGRect croppedRect = CGRectMake(offset.x, offset.y, image.size.width * zoomReciprocal, image.size.height * zoomReciprocal);
CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);
UIImage* croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];
CGImageRelease(croppedImageRef);
return croppedImage;
}
How do i share image from imageView. Here is my code for imageView:
UIImage *myImage = [UIImage imageNamed:[NSString stringWithFormat:
#"image%d.jpg", i]];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
[myImageView setFrame:CGRectMake(xOrigin, 0,
self.view.frame.size.width,
self.view.frame.size.height)];
_postImage.image = myImage;
}
- (IBAction)shareButtonPressed:(id)sender {
NSArray *activityItems;
if (_postImage.image != nil) {
activityItems = #[_postImage.image];
}
UIActivityViewController *activityVC = [[UIActivityViewController alloc]
initWithActivityItems:activityItems
applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
}
I get error - No share action available.Thanks in advance.
You probably forgot to initialize _postImage. Try to replace:
_postImage.image = myImage;
with:
_postImage = [[UIImageView alloc] initWithImage:myImage];
To get your image on activityViewController you need to create your custom Activity with that image which you want to show. Following are step's to create and show your custom activity with your image.
1.Create a new file subclassing UIActivity namely, "CustomActivity". Then in the CustomActivity.m file you need to write down following method.
- (NSString *)activityType {
return #"yourappname.Review.App"; //type
}
- (NSString *)activityTitle {
return #"Review App"; //title for activity
}
- (UIImage *)activityImage {
return [UIImage imageNamed:#"Icon.png"]; //image
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems {
NSLog(#"%s", __FUNCTION__);
return YES;
}
- (void)prepareWithActivityItems:(NSArray *)activityItems {
NSLog(#"%s",__FUNCTION__);
}
- (UIViewController *)activityViewController {
NSLog(#"%s",__FUNCTION__);
return nil;
}
- (void)performActivity {
//What your cust activity woudl perform when user tap onto it.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.apple.com/"]];
[self activityDidFinish:YES];
}
Then in your mainVC you could import this class and add below lines to use this custom activity.
NSString *textItem = #"provide your string";
UIImage *imageToShare = [UIImage imageNamed:#"Icon.png"]; //Provide your activity image
NSArray *items = [NSArray arrayWithObjects:textItem,imageToShare,nil];
custAct = [[CustomActivity alloc]init];
UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:#[custAct]];
[self presentViewController:controller animated:YES completion:nil];
Now you would be able to see your image with activity that you want to perform.
If my understanding is wrong, do correct me.
I tried implementing this answer: https://stackoverflow.com/a/22716610, to the problem of adding overlays to mkmapsnapshotter in iOS7 (cant do renderInContext method). I did this as shown below, but the image returned has only the map with no overlays. Forgive me, I am quite new to this. Thanks.
-(void)mapViewDidFinishRenderingMap:(MKMapView *)mapView fullyRendered:(BOOL)fullyRendered
{
if (mapView.tag == 100) {
MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = mapView.region;
options.size = mapView.frame.size;
options.scale = [[UIScreen mainScreen] scale];
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
if (error) {
NSLog(#"[Error] %#", error);
return;
}
UIImage *image = snapshot.image;
UIGraphicsBeginImageContextWithOptions(image.size, YES, image.scale);
{
[image drawAtPoint:CGPointMake(0, 0)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context,5.0f);
CGContextBeginPath(context);
bool first = YES;
NSArray *overlays = mapView.overlays;
for (id <MKOverlay> overlay in overlays) {
CGPoint point = [snapshot pointForCoordinate:overlay.coordinate];
if(first)
{
first = NO;
CGContextMoveToPoint(context,point.x, point.y);
}
else{
CGContextAddLineToPoint(context,point.x, point.y);
}
}
UIImage *compositeImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *data = UIImagePNGRepresentation(compositeImage);
placeToSave = data;
NSLog(#"MapView Snapshot Saved.");
//show image for debugging
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 200, 320, 320)];
imageView.image = compositeImage;
[self.view addSubview:imageView];
}
UIGraphicsEndImageContext();
}];
[mapView setHidden:YES];
}
}
cocos2d Using camera to take picture and save that to file
I can use camera to take picture.
But this picture is a part of this picture.(a white White border)
How get a big picture?
I want to get a clear picture.
thank you!!
-(void)takePhoto{
AppController *appdel = (AppController*) [[UIApplication sharedApplication] delegate];
#try {
uip = [[UIImagePickerController alloc] init] ;
uip.sourceType = UIImagePickerControllerSourceTypeCamera;
uip.allowsEditing = YES;
uip.delegate = self;
}
#catch (NSException * e) {
[uip release];
uip = nil;
}
#finally {
if(uip) {
[appdel.navController presentModalViewController:uip animated:YES];
}
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
profileImage=[info objectForKey:UIImagePickerControllerCropRect];
AppController *appdel = (AppController*) [[UIApplication sharedApplication] delegate];
[appdel.navController dismissModalViewControllerAnimated:YES];
[uip release];
[NSThread detachNewThreadSelector:#selector(writeImgToPath:) toTarget:self withObject:profileImage];
}
-(void)writeImgToPath:(id)sender
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
UIImage *image = sender;
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
CGSize size;
int currentProfileIndex = 1;
NSString *path = [[pathArr objectAtIndex:0]
stringByAppendingPathComponent:[NSString stringWithFormat:#"Img_%d.png",currentProfileIndex]];
size = CGSizeMake(1320, 480);
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, 1320, 480)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#”Saved…..”);
CGRect r = CGRectMake(0, 0, 1320, 480);
UIGraphicsBeginImageContext(r.size);
UIImage *img1;
[image drawInRect:r];
img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(img1, nil, nil, nil);
[pool release];
}
-(id) init
{
[self takePhoto];
}
return self;
}
I'm using IImagePickerController to get photos from the photo library. Works great on the iphone, but won't work on an iPad. There were solutions suggested to use UIpopoverController. I was using UIpopoverController in any earlier version, and I couldn't get it to work. Keep getting an error that the popoverController did not exist. Below is my code. Is there a framework that allows you to use UIPopoverController?
- (IBAction)getPhoto4:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage ,(NSString *)kUTTypeMovie];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = info[UIImagePickerControllerOriginalImage];
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 320.0/480.0;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 480.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 480.0;
}
else{
imgRatio = 320.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 320.0;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Get the data for the image
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
// Give a name to the file
IMAGE_COUNTER = IMAGE_COUNTER + 1;
NSString* incrementedImgStr = [NSString stringWithFormat: #"zTempDataFilePleaseDelete%d.jpg", IMAGE_COUNTER];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile2 = [documentsDirectory stringByAppendingPathComponent:incrementedImgStr];
if(IMAGE_COUNTER == 4) {
imageView4.image = img;
photoHeight4 = img.size.height;
photoWidth4 = img.size.width;
photoPath4 = fullPathToFile2;
}
// and then we write it out
[imageData writeToFile:fullPathToFile2 atomically:NO];
}
-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Save failed"
message: #"Failed to save image"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker1
{
[self dismissViewControllerAnimated:YES completion:nil];
}
On iPad you need to display UIImagePickerController embedded in UIPopoverController.
You can't directly display it using presentViewController:
If you are displaying camera then you can use presentViewController, else you need to use a popover for displaying the image picker in iPad.
Reference:
UIImagePickerController
So instead of:
[self presentViewController:imagePicker animated:YES completion:nil];
Use:
UIPopoverController *photoPop = [[UIPopoverController alloc]initWithContentViewController:imagePicker];
[photoPop presentPopoverFromRect:CGRectMake(100,100,300,300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
Check these tutorials:
UIImagePickerController
UIImagePickerController in iPad
try this code:
in .h file implement delegate
UIImagePickerControllerDelegate,UIPopoverControllerDelegate,UINavigationControllerDelegate
in .m file:
#implementation UIImagePickerController(Nonrotating)
- (BOOL)shouldAutorotate {
return NO;
}
#end
#implementation UINavigationController (Rotation_IOS6)
-(NSUInteger) supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotate
{
return [[self.viewControllers lastObject] shouldAutorotate];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}
#end
-(void)photoclick
{
UIImagePickerController *pckrImage=[[UIImagePickerController alloc]init];
pckrImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
pckrImage.allowsEditing = YES;
pckrImage.delegate=self;
// UITableViewCell *cell = [tblIncident cellForRowAtIndexPath:[tblIncident indexPathForSelectedRow]];
UIPopoverController * poppickePhoto = [[UIPopoverController alloc]initWithContentViewController:pckrImage];
poppickePhoto.delegate = self;
// poppickePhoto.popoverContentSize =CGSizeMake(320,480);
[poppickePhoto presentPopoverFromRect:yourbtn.frame inView:yourbtn.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
update
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *choosedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
yourumageview.image=choosedImage;
[poppickePhoto dismissPopoverAnimated:YES];
}