I'm doing an application that on a specific part of the application, the user will be able to take a picture from the camera or select from the Album and this image will be shown on the ViewController.
This is kind of easy, but, what I need, that I'm not being able to do is:
-I don't want that the Camera open full screen, I want it to 'open' on the ViewController that the user is, in the exactly same place as where the image will be, inside a circle.
I was able to make the Camera not open full screen, but I'm not being able to put this view inside the circle view and crop the photo according to the circle.
Here is my code, it might work if you create a standard project and I think that will help to understand what's going on:
VARIABLES
#property (nonatomic, strong) UIImagePickerController * picker;
#property (nonatomic, strong) UIImageView * photoView;
#property (nonatomic, strong) UIView * overlayView;
#property (nonatomic, strong) UIButton * takePhotoButton; //- function
#property (nonatomic, strong) UIButton * selectPhotoButton;
#property (nonatomic, strong) UIButton * takePicture; //- action
CODE
#interface CameraViewController ()
{
BOOL isFromAlbum;
}
#end
#implementation CameraViewController
#synthesize photoView;
#synthesize picker;
#synthesize takePicture;
#synthesize selectPhotoButton;
#synthesize takePhotoButton;
#synthesize overlayView;
#synthesize switchCameraButton;
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface
{
[super addBackButton];
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
//[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
//[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = CGRectMake(0, 0, 320, 320);
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
self.photoView.userInteractionEnabled = YES;
}
#pragma mark -
#pragma mark Button's Actions
- (void)takePhotoFunction
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
self.picker.view.frame = self.photoView.bounds;
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 70, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
self.switchCameraButton = [[UIButton alloc] init];
self.switchCameraButton.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.origin.y, 70, 70);
[self.switchCameraButton addTarget:self action:#selector(switchCamera:) forControlEvents:UIControlEventTouchUpInside];
[self.switchCameraButton setBackgroundImage:[UIImage imageNamed:#"reverse-camera-btn"] forState:UIControlStateNormal];
[self.photoView addSubview:self.switchCameraButton];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender
{
[self.picker takePicture];
}
-(IBAction)switchCamera:(id)sender
{
if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
else if (picker.cameraDevice == UIImagePickerControllerCameraDeviceRear)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO)
{
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage)
{
imageToSave = editedImage;
}
else
{
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.switchCameraButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
CGFloat minimumSide = fminf(imageToSave.size.width, imageToSave.size.height);
CGFloat finalSquareSize = 640.;
//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);
//draw
[imageToSave drawInRect:CGRectMake((minimumSide - originalImage.size.width)*scalingRatio/2., (minimumSide - originalImage.size.height)*scalingRatio/2., originalImage.size.width*scalingRatio, originalImage.size.height*scalingRatio)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//[self.photoView setImage:imageToSave];
[self.photoView setImage:croppedImage];
}
else
{
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker
{
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
With the code below, I get the following results:
A single view with a dark blue background.
2 green circles (the buttons)
Tapping on the left circle puts the camera's "sight" inside of it.
Tapping on the "take" button (at the bottom of the circle on the left) fires off the "takePhotoAction" method.
[Code]
// ViewController.m
#import "ViewController.h"
#interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
BOOL isFromAlbum;
}
#property (nonatomic, strong) UIImagePickerController * picker;
#property (nonatomic, strong) UIImageView * photoView;
#property (nonatomic, strong) UIView * overlayView;
#property (nonatomic, strong) UIButton * takePhotoButton; //- function
#property (nonatomic, strong) UIButton * selectPhotoButton;
#property (nonatomic, strong) UIButton * takePicture; //- action
#end
#implementation ViewController
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface {
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = self.takePhotoButton.frame;
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
[self.photoView setUserInteractionEnabled:YES];
}
#pragma mark -
#pragma mark Actions
- (void)takePhotoFunction {
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
self.picker.view.frame = self.photoView.bounds;
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 40, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto {
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender {
[self.picker takePicture];
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
[self.photoView setImage:imageToSave];
} else {
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker {
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
#end
Solved the issue of the "smaller image" on the PhotoView after taking a picture by cropping it as a square and just after, set the image of the PhotoView.
Solved the issue of the image "going up" a little bit after setting the image on PhotoView by 'setting' the picker.view frame on x: 0, y:-50, PhotoView.width, PhotoView.height.
Here is the fullcode:
#interface CameraViewController ()
{
BOOL isFromAlbum;
}
#end
#implementation CameraViewController
#synthesize photoView;
#synthesize picker;
#synthesize takePicture;
#synthesize selectPhotoButton;
#synthesize takePhotoButton;
#synthesize switchCameraButton;
#pragma mark -
#pragma mark Initialization & Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self initInterface];
}
-(void)initInterface
{
[super addBackButton];
self.view.backgroundColor = [UIColor colorWithRed:026.0f/255.0f green:030.0f/255.0f blue:055.0f/255.0f alpha:1.0f];
self.takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePhotoButton.frame = CGRectMake(27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.takePhotoButton.layer.cornerRadius = self.takePhotoButton.frame.size.width / 2.0f;
[self.takePhotoButton setImage:[UIImage imageNamed:#"take-photo-btn"] forState:UIControlStateNormal];
[self.takePhotoButton addTarget:self action:#selector(takePhotoFunction) forControlEvents:UIControlEventTouchUpInside];
//[self.takePhotoButton setBackgroundColor:[UIColor colorWithRed:000.0f/255.0f green:255.0f/255.0f blue:000.0f/255.0f alpha:0.25f]];
[self.view addSubview:self.takePhotoButton];
self.selectPhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.selectPhotoButton.frame = CGRectMake(self.view.frame.size.width/2 + 27.5f, self.view.frame.size.width/2 - 55, 110, 110);
self.selectPhotoButton.layer.cornerRadius = self.selectPhotoButton.frame.size.width / 2.0f;
[self.selectPhotoButton setImage:[UIImage imageNamed:#"pick-photo-btn"] forState:UIControlStateNormal];
[self.selectPhotoButton addTarget:self action:#selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
//[self.selectPhotoButton setBackgroundColor:[UIColor colorWithRed:0 green:255/255.0f blue:0 alpha:0.25f]];
[self.view addSubview:self.selectPhotoButton];
self.photoView = [[UIImageView alloc] init];
self.photoView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:000.0f/255.0f blue:000.0f/255.0f alpha:0.25f];
self.photoView.frame = CGRectMake(0, 0, 320, 320);
self.photoView.layer.cornerRadius = self.photoView.frame.size.width / 2;
self.photoView.layer.masksToBounds = YES;
self.photoView.userInteractionEnabled = YES;
}
#pragma mark -
#pragma mark Button's Actions
- (void)takePhotoFunction
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.showsCameraControls = NO;
//self.picker.view.frame = self.photoView.bounds;
self.picker.view.frame = CGRectMake(0, -50, photoView.frame.size.width, photoView.frame.size.height + 50);
[self.photoView addSubview:self.picker.view];
self.takePicture = [UIButton buttonWithType:UIButtonTypeSystem];
self.takePicture.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.size.height - 70, 70, 70);
[self.takePicture addTarget:self action:#selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
[self.takePicture setBackgroundImage:[UIImage imageNamed:#"take-photo-action"] forState:UIControlStateNormal];
[self.photoView addSubview:self.takePicture];
self.switchCameraButton = [[UIButton alloc] init];
self.switchCameraButton.frame = CGRectMake(self.photoView.frame.size.width/2 - 35, self.photoView.frame.origin.y, 70, 70);
[self.switchCameraButton addTarget:self action:#selector(switchCamera:) forControlEvents:UIControlEventTouchUpInside];
[self.switchCameraButton setBackgroundImage:[UIImage imageNamed:#"reverse-camera-btn"] forState:UIControlStateNormal];
[self.photoView addSubview:self.switchCameraButton];
[self.view addSubview:self.photoView];
isFromAlbum = NO;
}
- (void)selectPhoto
{
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.allowsEditing = YES;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isFromAlbum = YES;
[self presentViewController:self.picker animated:YES completion:NULL];
}
-(IBAction)takePhotoAction:(id)sender
{
[self.picker takePicture];
}
-(IBAction)switchCamera:(id)sender
{
if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
else if (picker.cameraDevice == UIImagePickerControllerCameraDeviceRear)
{
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
}
- (UIImage*)rotateUIImage:(UIImage*)sourceImage
{
CGSize size = sourceImage.size;
UIGraphicsBeginImageContext(CGSizeMake(size.height, size.width));
[[UIImage imageWithCGImage:[sourceImage CGImage] scale:1.0 orientation:UIImageOrientationDownMirrored] drawInRect:CGRectMake(0,0,size.height ,size.width)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark -
#pragma mark PickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)myPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
//if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
if (isFromAlbum == NO)
{
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage)
{
imageToSave = editedImage;
}
else
{
imageToSave = originalImage;
}
// Save the new image (original or edited) to the Camera Roll
//UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
[self.takePhotoButton removeFromSuperview];
[self.switchCameraButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
[self.picker.view removeFromSuperview];
[self.takePicture removeFromSuperview];
CGFloat minimumSide = fminf(imageToSave.size.width, imageToSave.size.height);
CGFloat finalSquareSize = 640.;
//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);
//draw
[imageToSave drawInRect:CGRectMake((minimumSide - originalImage.size.width)*scalingRatio/2., (minimumSide - originalImage.size.height)*scalingRatio/2., originalImage.size.width*scalingRatio, originalImage.size.height*scalingRatio)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront)
// {
// [self rotateUIImage:croppedImage];
// }
//[self.photoView setImage:imageToSave];
[self.photoView setImage:croppedImage];
}
else
{
[self.takePhotoButton removeFromSuperview];
[self.selectPhotoButton removeFromSuperview];
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self.photoView setImage:chosenImage];
[self.view addSubview:self.photoView];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)myPicker
{
//[picker.view removeFromSuperview];
[myPicker dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark -
#pragma mark NavigationController Methods
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:NO];
}
#end
Related
I want to develop a application in which user can change there hair style. so i add a overlay in camera view by using following code files and try to combine both image.
Here is my ViewController.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverControllerDelegate>{
UIImagePickerController *imagePicker;
UIPopoverController *popoverController;
NSData *imageData;
}
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#end
and ViewController.m file
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// assign action to button
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(0, 0, 200, 60);
myButton.center = self.view.center;
[myButton addTarget:self action:#selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:#"Image Picker" forState:UIControlStateNormal];
[self.view addSubview:myButton];
}
- (void)buttonPress:(id)sender {
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// alert the user that the camera can't be accessed
UIAlertView *noCameraAlert = [[UIAlertView alloc] initWithTitle:#"No Camera" message:#"Unable to access the camera!" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[noCameraAlert show];
} else {
// prepare imagePicker view
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
imagePicker.delegate = self;
imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
imagePicker.navigationBarHidden = YES;
imagePicker.toolbarHidden = YES;
imagePicker.extendedLayoutIncludesOpaqueBars = YES;
// create view for overlay
CGRect overlayRect = CGRectMake(0, 0, imagePicker.view.frame.size.width, imagePicker.view.frame.size.height-50);
UIView *overlayView = [[UIView alloc] initWithFrame:overlayRect];
// prepare the image to overlay
UIImageView *overlayImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"wig"]];
overlayImage.center = overlayView.center;
//overlayImage.alpha = 0.5;
[overlayView addSubview:overlayImage];
// add the image as the overlay
[imagePicker setCameraOverlayView:overlayView];
// display imagePicker
[self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}
}
#pragma mark - UIBarButton Selectors
- (void)takePictureButtonPressed:(id)sender {
NSLog(#"takePictureButtonPressed...");
// TODO: take picture!
[self presentViewController:imagePicker animated:YES
completion:^ {
[imagePicker takePicture];
}];
}
- (void)startStopButtonPressed:(id)sender {
NSLog(#"startStopButtonPressed...");
// TODO: make this do something
}
- (void)timedButtonPressed:(id)sender {
NSLog(#"timedButtonPressed...");
// TODO: implement timer before calling takePictureButtonPressed
}
- (void)cancelButtonPressed:(id)sender {
NSLog(#"cancelButtonPressed");
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UIImagePickerController Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)editingInfo {
[picker dismissViewControllerAnimated:YES completion:NULL];
[popoverController dismissPopoverAnimated: YES];
NSData *image1 = UIImageJPEGRepresentation([editingInfo valueForKey:UIImagePickerControllerOriginalImage],1.0);
UIImage *Imgg = [self addOverlayToBaseImage:[editingInfo valueForKey:UIImagePickerControllerOriginalImage]];
image1 = UIImageJPEGRepresentation(Imgg,1.0);
imageData = image1;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",#"cached"]];
NSLog((#"pre writing to file"));
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
[[NSUserDefaults standardUserDefaults] setValue:imagePath forKey:#"imagePath"];
NSLog(#"the cachedImagedPath is %#",imagePath);
}
[self.imageView setImage:Imgg];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIImage*)addOverlayToBaseImage:(UIImage*)baseImage{
UIImage *overlayImage = [UIImage imageNamed:#"wig.png"];
CGPoint topCorner = CGPointMake(0, 0);
CGSize targetSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
CGRect scaledRect = CGRectZero;
CGFloat scaledX = self.view.frame.size.height * baseImage.size.width / baseImage.size.height;
CGFloat offsetX = (scaledX - self.view.frame.size.width) / -2;
scaledRect.origin = CGPointMake(offsetX, 0.0);
scaledRect.size.width = scaledX;
scaledRect.size.height = self.view.frame.size.height;
UIGraphicsBeginImageContext(targetSize);
[baseImage drawInRect:scaledRect];
[overlayImage drawAtPoint:topCorner];
UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
#end
This code combine both image but i want the exact same image which user can see in camera preview. My problem is when i capture image and see image in UIImageview its totally different from camera preview.
Camera Preview Image
What i get
Help me to get same image like Camera preview.
I was also facing the same issue. I have fixed this issue here you can find my complete git repo
Camera Preview Image
What i get
How to get the black blocks disappear?
And after the rotation, the black blocks disappear.
AppDelegate Source File:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = viewController;
bar = [KodUserCenterBar instance];
[self.window makeKeyAndVisible];
return YES;
}
Header File:
#interface KodUserCenterBar : UIWindow
/**获取单例
*/
+ (instancetype)instance;
/**显示工具栏
*/
+ (void)show;
/**隐藏工具栏
*/
+ (void)hide;
/**显示功能视图
*/
+ (void)showFunctionView;
/**隐藏功能视图
*/
+ (void)hideFunctionView;
#end
Source File:
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kBarWidth 200
#define kBarImageViewTag 100
#define kBarItemGap 5
#define degreesToRadian(x) (M_PI * (x) / 180.0)
#interface KodUserCenterBarFunctionItemObject : NSObject
#property (nonatomic, copy) NSString *title;
#property (nonatomic, assign) NSUInteger indexOfTabBar;
#property (nonatomic, copy) NSString *imageName;
+ (instancetype)objectWithTitle:(NSString *)title indexOfTabBar:(NSUInteger)index imageName:(NSString *)imageName;
#end
#implementation KodUserCenterBarFunctionItemObject
+ (instancetype)objectWithTitle:(NSString *)title indexOfTabBar:(NSUInteger)index imageName:(NSString *)imageName
{
KodUserCenterBarFunctionItemObject *obj = [KodUserCenterBarFunctionItemObject new];
if (obj) {
obj.title = title;
obj.indexOfTabBar = index;
obj.imageName = imageName;
}
return obj;
}
#end
#interface KodUserCenterBar()
{
UIPanGestureRecognizer *pan;
UIViewController *_rootVC;
}
#property (nonatomic, copy) NSArray *itemsOfBar;
#property (nonatomic, assign) CGFloat initWidth;
#property (atomic, strong) UIButton *button;
#end
static KodUserCenterBar *static_instance = nil;
static BOOL isShowMenu = NO;
#implementation KodUserCenterBar
+ (instancetype)instance
{
if (static_instance == nil) {
static_instance = [KodUserCenterBar new];
[static_instance addTopButton];
}
return static_instance;
}
+ (void)show
{
[KodUserCenterBar instance].hidden = NO;
}
+ (void)hide
{
[KodUserCenterBar instance].hidden = YES;
}
+ (void)showFunctionView
{
if (!isShowMenu) {
[[KodUserCenterBar instance] clickBar:nil];
}
}
+ (void)hideFunctionView
{
if (isShowMenu) {
[[KodUserCenterBar instance] clickBar:nil];
}
}
- (instancetype)init
{
if (self = [super init]) {
self.backgroundColor = [UIColor clearColor];
self.windowLevel = UIWindowLevelAlert;
self.userInteractionEnabled = YES;
[self makeKeyAndVisible];
self.sd_x = 0;
self.sd_center_y = [UIScreen mainScreen].bounds.size.height / 2;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onDeviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}
return self;
}
- (NSArray *)itemsOfBar
{
if (_itemsOfBar == nil) {
KodUserCenterBarFunctionItemObject *item1 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"个人中心" indexOfTabBar:0 imageName:#"tb3_toolbaruser"];
KodUserCenterBarFunctionItemObject *item2 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"游戏礼包" indexOfTabBar:1 imageName:#"tb3_toolbargame"];
KodUserCenterBarFunctionItemObject *item3 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"系统公告" indexOfTabBar:2 imageName:#"tb3_toolbarmsg"];
KodUserCenterBarFunctionItemObject *item4 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"游戏论坛" indexOfTabBar:3 imageName:#"tb3_toolbarbbs"];
NSArray *data = #[item1, item2, item3, item4];
_itemsOfBar = [NSArray arrayWithArray:data];
}
return _itemsOfBar;
}
- (void)onDeviceOrientationChange
{
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"is portrait");
NSLog(#"width = %f, height = %f", kScreenWidth, kScreenHeight);
[self adjustWindowPosition];
self.sd_center_y = kScreenHeight / 2;
}
else if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight) {
NSLog(#"is landscape");
NSLog(#"width = %f, height = %f", kScreenWidth, kScreenHeight);
[self adjustWindowPosition];
self.sd_center_y = kScreenHeight / 2;
}
}
- (void)addTopButton
{
pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(dragBar:)];
pan.delaysTouchesBegan = NO;
[self addGestureRecognizer:pan];
UIViewController *vc = [[KodBasicViewController alloc] init];
vc.view.backgroundColor = [UIColor clearColor];
self.rootViewController = vc;
CGSize size = [UIImage imageNamed:#"tb3_assi_nor"].size;
self.sd_width = size.width;
self.sd_height = size.height;
self.initWidth = size.width;
_button = [[UIButton alloc] init];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
_button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[_button addTarget:self action:#selector(clickBar:) forControlEvents:UIControlEventTouchUpInside];
_button.userInteractionEnabled = YES;
_button.selected = NO;
[_button becomeFirstResponder];
[vc.view addSubview:_button];
}
- (void)clickBar:(id)button
{
NSTimeInterval interval = 0.2;
__weak typeof(_button) weakButton = _button;
isShowMenu = !isShowMenu;
pan.enabled = !isShowMenu;
if (self.sd_center_x > kScreenWidth / 2) {
[UIView animateWithDuration:interval animations:^{
self.sd_x = kScreenWidth;
} completion:^(BOOL finished) {
if (isShowMenu) {
self.sd_width = kBarWidth + self.initWidth;
_button.sd_right_x = self.sd_width;
UIImage *image = [UIImage imageNamed:#"tb3_assi_bor_right"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 30, 1, 0)];
UIImageView *rightImageView = [[UIImageView alloc] initWithImage:image];
rightImageView.image = image;
rightImageView.sd_width = kBarWidth;
rightImageView.sd_right_x = _button.sd_x;
rightImageView.sd_center_y = _button.sd_center_y;
rightImageView.tag = kBarImageViewTag;
rightImageView.userInteractionEnabled = YES;
[self.rootViewController.view addSubview:rightImageView];
self.sd_x = kScreenWidth;
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_right"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_right"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_right"] forState:UIControlStateHighlighted];
[self addFunctionItems:NO];
}
else {
self.sd_width = self.initWidth;
_button.sd_right_x = self.sd_width;
UIView *contentView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
[contentView removeFromSuperview];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
}
[UIView animateWithDuration:interval animations:^{
self.sd_right_x = kScreenWidth;
}];
}];
}
else {
[UIView animateWithDuration:interval animations:^{
self.sd_right_x = 0;
} completion:^(BOOL finished) {
if (isShowMenu) {
self.sd_width = kBarWidth + self.initWidth;
UIImage *image = [UIImage imageNamed:#"tb3_assi_bor_left"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 0, 1, 30)];
UIImageView *leftImageView = [[UIImageView alloc] initWithImage:image];
leftImageView.image = image;
leftImageView.sd_width = kBarWidth;
leftImageView.sd_x = _button.sd_right_x;
leftImageView.sd_center_y = _button.sd_center_y;
leftImageView.tag = kBarImageViewTag;
leftImageView.userInteractionEnabled = YES;
[self.rootViewController.view addSubview:leftImageView];
self.sd_right_x = 0;
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_left"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_left"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_left"] forState:UIControlStateHighlighted];
[self addFunctionItems:YES];
}
else {
self.sd_width = self.initWidth;
UIView *contentView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
[contentView removeFromSuperview];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
}
[UIView animateWithDuration:interval animations:^{
self.sd_x = 0;
}];
}];
}
}
- (void)addFunctionItems:(BOOL)isLeft
{
UIView *bgView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
if (bgView) {
[self.itemsOfBar enumerateObjectsUsingBlock:^(KodUserCenterBarFunctionItemObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([bgView viewWithTag:idx] == nil) {
KodFrameTabBarItem *item = [[KodFrameTabBarItem alloc] init];
item.tag = idx;
item.title = obj.title;
item.imageName = obj.imageName;
item.sd_width = (bgView.sd_width - _itemsOfBar.count * kBarItemGap - 10) / _itemsOfBar.count;
item.sd_height = bgView.sd_height;
item.sd_center_y = bgView.sd_height / 2;
item.sd_center_x = kBarItemGap + idx * (item.sd_width + kBarItemGap) + item.sd_width / 2;
item.sd_center_x += isLeft ? 0 : item.sd_width / 4;
[item addTarget:self action:#selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
[bgView addSubview:item];
}
}];
}
}
- (void)clickItem:(id)sender
{
[KodNavigationView showWithIndex:0];
[[UIApplication sharedApplication].keyWindow addSubview:[KodNavigationView instance]];
}
- (void)adjustWindowPosition
{
if (self.sd_center_x < kScreenWidth / 2) {
self.sd_x = 0;
}
else {
self.sd_right_x = kScreenWidth;
}
}
- (void)dragBar:(UIPanGestureRecognizer *)p
{
CGPoint panPoint = [p locationInView:[[UIApplication sharedApplication] keyWindow]];
if (p.state == UIGestureRecognizerStateBegan) {
if (_button) {
_button.selected = YES;
}
}
else if(p.state == UIGestureRecognizerStateChanged) {
self.center = CGPointMake(panPoint.x, panPoint.y);
if (panPoint.x < WIDTH / 2) {
self.sd_x = 0;
}
else if (panPoint.x > kScreenWidth - WIDTH / 2) {
self.sd_right_x = kScreenWidth;
}
if (panPoint.y < HEIGHT / 2) {
self.sd_y = 0;
}
else if (panPoint.y > kScreenHeight - HEIGHT / 2) {
self.sd_bottom_y = kScreenHeight;
}
}
else if(p.state == UIGestureRecognizerStateEnded) {
if(panPoint.x <= kScreenWidth / 2) {
[UIView animateWithDuration:0.2 animations:^{
self.sd_x = 0;
} completion:nil];
}
else {
[UIView animateWithDuration:0.2 animations:^{
self.sd_right_x = kScreenWidth;
} completion:nil];
}
if (_button) {
_button.selected = NO;
}
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#end
Root ViewController
Source File Of Root ViewController:
#interface KodBasicViewController ()
#end
#implementation KodBasicViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
UIWindow *window = self.view.window;
[window bringSubviewToFront:window.rootViewController.view];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
UIWindow *window = self.view.window;
[window bringSubviewToFront:window.rootViewController.view];
}
#end
Here is my solution to this problem:
window.layer.masksToBounds = true
It's the default background colour of UIWindow instance, and while your root view is doing rotation, those uncovered parts will be shown as black block as you said.
You can just set your desired background colour for your window (or make your root view's frame big enough to cover whole window while doing rotation, not recommended):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
[self.window setBackgroundColor:[UIColor lightGrayColor]];
[self.window makeKeyAndVisible];
return YES;
}
I am making an app for iPhone and want to give users the ability to multiselect images from their photo-library. I already have a working code for user to select four images at a time.
But I can't select 1 or 2 or 3 images at a time. I want to select the 1 or 2 or 3 images at a time.
This is my code. I have struggled for 3 days without finding a solution. Please help me anybody.
Thanks in advance.............
-(void)choosePhotoFromExistingImages
{
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
elcPicker.maximumImagesCount = 4;
elcPicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
elcPicker.imagePickerDelegate = self;
[self presentViewController:elcPicker animated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self.navigationController dismissViewControllerAnimated: YES completion: nil];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithStyle:UITableViewStylePlain];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.maximumImagesCount = 0;
elcPicker.imagePickerDelegate = self;
elcPicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
tablePicker.parent = elcPicker;
// Move me
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
[self presentViewController:elcPicker animated:YES completion:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
return YES;
}
else
{
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImagePickerControllerDelegate Methods
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
CGRect workingFrame = _scrollView.frame;
workingFrame.origin.x = 0;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
for (NSDictionary *dict in info)
{
UIImage *image = [dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[self.view addSubview:imageview ];
self.chosenImages = images;
}
UIImageView *image1=[[UIImageView alloc]initWithFrame:CGRectMake(10, 240, 40, 40)];
image1.image=[images objectAtIndex:0];
[self.view addSubview:image1];
UIImageView *image2=[[UIImageView alloc]initWithFrame:CGRectMake(60, 240, 40, 40)];
image2.image=[images objectAtIndex:1];
[self.view addSubview:image2];
UIImageView *image3=[[UIImageView alloc]initWithFrame:CGRectMake(120, 240, 40, 40)];
image3.image=[images objectAtIndex:2];
[self.view addSubview:image3];
UIImageView *image4=[[UIImageView alloc]initWithFrame:CGRectMake(180, 240, 40, 40)];
image4.image=[images objectAtIndex:3];
[self.view addSubview:image4];
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
Here is the link for the Tutorial. Its works fine in my project.Try this
Hope its useful for you.
Check your code in - (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
For example, you create array with length of 2, but in code below you try to get image3.image=[images objectAtIndex:2]; and image4.image=[images objectAtIndex:3];. It's not a surprise that your code throws exception.
Good luck!
I'm using Interface Builder to design a static table view:
The orange bar is a custom subclassed view. Each other view is retained the same way, but for some reason only my custom view disappears. Trying to access it's properties later leads to a null for things I explicitly set, but no EXEC_BAD_ACCESS's.
Custom View code:
#import "EditableLabel.h"
#implementation EditableLabel
#synthesize font;
#synthesize maxSize;
#synthesize textColor;
- (void)awakeFromNib{
[self innerInit];
}
- (id)initWithFrame:(CGRect)frame
{
NSLog(#"got init");
self = [super initWithFrame:frame];
if (self) {
[self innerInit];
}
return self;
}
-(void)innerInit{
self.font = [UIFont systemFontOfSize:[UIFont systemFontSize]]; //default sys font, set this for pretty
self.maxSize = self.frame.size; //set this for pretty too
self.textColor = [UIColor blackColor];
self.isEditting = NO;
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
self.button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
self.button.userInteractionEnabled=YES;
self.button.hidden=NO;
self.button.titleLabel.font=font;
[self.button setTitleColor:textColor forState:UIControlStateNormal];
[self.button addTarget:self action:#selector(edit) forControlEvents:UIControlEventTouchUpInside];
[self.button setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self.button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self addSubview:self.button];
self.editField = [[UITextField alloc] initWithFrame:self.button.frame];
self.editField.font=font;
self.editField.textColor = textColor;
self.editField.userInteractionEnabled=YES;
self.editField.hidden=YES;
self.editField.borderStyle = UITextBorderStyleRoundedRect;
[self.editField addTarget:self action:#selector(finishEditting) forControlEvents:UIControlEventEditingDidEnd];
[self.editField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self.editField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self addSubview:self.editField];
[self bringSubviewToFront:self.button];
}
-(void)setTextFieldDelegate:(id)viewcontroller{
self.editField.delegate = viewcontroller;
}
-(void)edit{
[self flipWithCompletionBlock:^(BOOL done){
if (done){
self.isEditting=YES;
self.button.enabled=NO;
}
}];
}
-(void)finishEditting{
[self flipWithCompletionBlock:^(BOOL done){
if (done){
self.isEditting=NO;
self.button.enabled=YES;
[self.button setTitle:self.editField.text forState:UIControlStateNormal];
}
}];
}
-(NSString*)text{
return self.button.titleLabel.text;
}
-(void)setText:(NSString*)text{
self.editField.text=text;
[self.button setTitle:text forState:UIControlStateNormal];
}
-(UIColor*)backgroundColor{
return self.button.backgroundColor;
}
-(void)setBackgroundColor:(UIColor *)backgroundColor{
[self.button setBackgroundColor:backgroundColor];
[self.editField setBackgroundColor:backgroundColor];
}
-(void)setAlignmentVertical:(UIControlContentVerticalAlignment)vert horizontalAlignment:(UIControlContentHorizontalAlignment)horiz{
[self.button setContentHorizontalAlignment:horiz];
[self.button setContentVerticalAlignment:vert];
[self.editField setContentHorizontalAlignment:horiz];
[self.editField setContentVerticalAlignment:vert];
}
- (void)flipWithCompletionBlock:(void (^)(BOOL))block{
[UIView transitionWithView:self
duration:.3
options:UIViewAnimationOptionTransitionFlipFromTop
animations:^{
if (self.isEditting){
self.editField.hidden=YES;
self.button.hidden=NO;
[self bringSubviewToFront:self.button];
}
else {
self.button.hidden=YES;
self.editField.hidden=NO;
[self bringSubviewToFront:self.editField];
}
} completion:block];
}
#end
in my view controller.h I have #property (strong, nonatomic) IBOutlet EditableLabel *userNameEditField;, and every other view is retained fine. For some reason, only my subclass is released.
Hey. I've achieved making a programmatic UIScrollView with zooming, but now I've been trying to take the scrollable/zoomable image to an external screen if plugged in.
#implementation MapVC
UIScrollView *mapScrollView;
UIImageView *mapImageView;
UIImageView *mapImageViewEx;
CGFloat lastScale = 0;
NSMutableArray *map_List;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
map_List = [[NSMutableArray alloc] init];
[map_List addObject:#"Pacific_Map.png"];
[map_List addObject:#"Atlantic_Map.png"];
CGRect mapScrollViewFrame = CGRectMake(0, 0, 1024, 768);
mapScrollView = [[UIScrollView alloc] initWithFrame:mapScrollViewFrame];
mapScrollView.backgroundColor = [UIColor blackColor];
[mapScrollView setDelegate:(id<UIScrollViewDelegate>)self];
mapScrollView.contentSize = CGSizeMake(2437, 1536);
mapScrollView.bounces = NO;
mapScrollView.bouncesZoom = NO;
mapScrollView.minimumZoomScale = .5;
mapScrollView.maximumZoomScale = 1.5;
[mapScrollView setZoomScale:mapScrollView.minimumZoomScale];
UIImage *mapImage = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageView = [[UIImageView alloc] initWithImage: mapImage];
[mapImage release];
if(exScreenEnabled==1){
UIImage *mapImageEx = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageViewEx = [[UIImageView alloc] initWithImage: mapImageEx];
[mapImageEx release];
UIView *containerExViewP = (UIView*)[del.switchExVC.view viewWithTag:9000];
[containerExViewP addSubview:mapImageViewEx];
}else{
[mapScrollView addSubview:mapImageView];
}
[self addSubview:mapScrollView];
mapImageView.userInteractionEnabled = YES;
UIImage *footerMapIMG = [UIImage imageNamed:#"footer_map_alternate.png"];
UIImageView *footerMapView = [[UIImageView alloc] initWithImage:(UIImage *)footerMapIMG];
CGRect footerMapFrame = CGRectMake(0, 686, 213, 82);
footerMapView.frame = footerMapFrame;
[self addSubview:footerMapView];
footerMapView.image = footerMapIMG;
[footerMapView release];
CGRect backBTNFrame = CGRectMake(20, 714, 140, 52);
UIButton *MAP_backButton = [[UIButton alloc] init];
MAP_backButton.frame = backBTNFrame;
UIImage *MAP_backButtonIMG = [UIImage imageNamed:#"button_back.png"];
[MAP_backButton setImage:MAP_backButtonIMG forState:UIControlStateNormal];
MAP_backButton.backgroundColor = [UIColor clearColor];
[self addSubview:MAP_backButton];
[MAP_backButton release];
[MAP_backButton addTarget:del.switchVC
action:#selector(gotoMapAndListChooser)
forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
if(exScreenEnabled==1){
return mapImageViewEx;
}else{
return mapImageView;
}
}
(Sorry I've had no luck getting that formatted to look right on this site)
If a video cable is plugged into an iPad, there's no image on the iPad, which is what I want. The image on the external screen zooms correctly when you do the gesture on the iPad, but I can't figure out how to make it scroll. Thanks in advance.
edit: I now have this -
#implementation MapVC
UIScrollView *mapScrollView;
UIImageView *mapImageView;
UIImageView *mapImageViewEx;
CGFloat lastScale = 0;
NSMutableArray *map_List;
int touchesNum = 0;
-(void)touchesBegan:(NSSet *)theTouches withEvent:(UIEvent *)event {
NSSet *touches = [event allTouches];
touchesNum=[touches count];
NSLog(#"number of touches %i", touchesNum);
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
map_List = [[NSMutableArray alloc] init];
[map_List addObject:#"Pacific_Map.png"];
[map_List addObject:#"Atlantic_Map.png"];
CGRect mapScrollViewFrame = CGRectMake(0, 0, 1024, 768);
mapScrollView = [[UIScrollView alloc] initWithFrame:mapScrollViewFrame];
mapScrollView.backgroundColor = [UIColor blackColor];
[mapScrollView setDelegate:(id<UIScrollViewDelegate>)self];
mapScrollView.contentSize = CGSizeMake(2437, 1536);
mapScrollView.bounces = NO;
mapScrollView.bouncesZoom = NO;
mapScrollView.minimumZoomScale = .5;
mapScrollView.maximumZoomScale = 1.5;
[mapScrollView setZoomScale:mapScrollView.minimumZoomScale];
UIImage *mapImage = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageView = [[UIImageView alloc] initWithImage: mapImage];
[mapImage release];
if(exScreenEnabled==1){
UIImage *mapImageEx = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageViewEx = [[UIImageView alloc] initWithImage: mapImageEx];
[mapImageEx release];
UIView *containerExViewP = (UIView*)[del.switchExVC.view viewWithTag:9000];
[containerExViewP addSubview:mapImageViewEx];
}else{
[mapScrollView addSubview:mapImageView];
}
[self addSubview:mapScrollView];
mapImageView.userInteractionEnabled = YES;
UIImage *footerMapIMG = [UIImage imageNamed:#"footer_map_alternate.png"];
UIImageView *footerMapView = [[UIImageView alloc] initWithImage:(UIImage *)footerMapIMG];
CGRect footerMapFrame = CGRectMake(0, 686, 213, 82);
footerMapView.frame = footerMapFrame;
[self addSubview:footerMapView];
footerMapView.image = footerMapIMG;
[footerMapView release];
CGRect backBTNFrame = CGRectMake(20, 714, 140, 52);
UIButton *MAP_backButton = [[UIButton alloc] init];
MAP_backButton.frame = backBTNFrame;
UIImage *MAP_backButtonIMG = [UIImage imageNamed:#"button_back.png"];
[MAP_backButton setImage:MAP_backButtonIMG forState:UIControlStateNormal];
MAP_backButton.backgroundColor = [UIColor clearColor];
[self addSubview:MAP_backButton];
[MAP_backButton release];
[MAP_backButton addTarget:del.switchVC
action:#selector(gotoMapAndListChooser)
forControlEvents:UIControlEventTouchUpInside];
mapScrollView.multipleTouchEnabled = YES;
}
return self;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
if(exScreenEnabled==1){
return mapImageViewEx;
}else{
return mapImageView;
}
}
- (void)scrollViewDidScroll:(UIScrollView *)inscrollView{
if(touchesNum==0){
CGPoint p = mapScrollView.contentOffset;
mapImageViewEx.frame = CGRectMake((p.x*-1), (p.y*-1), mapImageViewEx.frame.size.width, mapImageViewEx.frame.size.height);
}
}
- (void)dealloc {
[mapScrollView release];
[mapImageView release];
[map_List release];
[super dealloc];
}
#end
As I said below, I can now get either scroll or zooming to work separately, but zooming is all messed up if scrolling is working, because when zooming it thinks it's also scrolling. So I want to avoid it scrolling when zooming, and to do this I want to detect the number of touches, which I must be doing wrong!
Got it working with the image being on the iPad and external screen. I'll probably swap it in with a rectangular area because the image is resource heavy to be both the iPad and external screen.
#import "exGlobal.h"
#import "mapVC.h"
#import "switchVC.h"
#import "switchExVC.h"
#import "mainMenuAppDelegate.h"
#import <MobileCoreServices/MobileCoreServices.h>
#implementation MapVC
UIScrollView *mapScrollView;
UIImageView *mapImageView;
UIImageView *mapImageViewEx;
CGFloat lastScale = 0;
NSMutableArray *map_List;
static int toggleScroll = 1;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
map_List = [[NSMutableArray alloc] init];
[map_List addObject:#"Pacific_Map.png"];
[map_List addObject:#"Atlantic_Map.png"];
CGRect mapScrollViewFrame = CGRectMake(0, 0, 1024, 768);
mapScrollView = [[UIScrollView alloc] initWithFrame:mapScrollViewFrame];
mapScrollView.backgroundColor = [UIColor blackColor];
[mapScrollView setDelegate:(id<UIScrollViewDelegate>)self];
mapScrollView.contentSize = CGSizeMake(2437, 1536);
mapScrollView.bounces = NO;
mapScrollView.bouncesZoom = NO;
mapScrollView.minimumZoomScale = .5;
mapScrollView.maximumZoomScale = 1.5;
[mapScrollView setZoomScale:mapScrollView.minimumZoomScale];
UIImage *mapImage = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageView = [[UIImageView alloc] initWithImage: mapImage];
[mapImage release];
if(exScreenEnabled==1){
UIImage *mapImageEx = [UIImage imageNamed:[map_List objectAtIndex:mapNum]];
mapImageViewEx = [[UIImageView alloc] initWithImage: mapImageEx];
[mapImageEx release];
UIView *containerExViewP = (UIView*)[del.switchExVC.view viewWithTag:9000];
[containerExViewP addSubview:mapImageViewEx];
[mapScrollView addSubview:mapImageView]; // see if this works ok on iPad. Map on TV AND iPad.
}else{
[mapScrollView addSubview:mapImageView];
}
[self addSubview:mapScrollView];
mapImageView.userInteractionEnabled = YES;
UIImage *footerMapIMG = [UIImage imageNamed:#"footer_map_alternate.png"];
UIImageView *footerMapView = [[UIImageView alloc] initWithImage:(UIImage *)footerMapIMG];
CGRect footerMapFrame = CGRectMake(0, 686, 213, 82);
footerMapView.frame = footerMapFrame;
[self addSubview:footerMapView];
footerMapView.image = footerMapIMG;
[footerMapView release];
CGRect backBTNFrame = CGRectMake(20, 714, 140, 52);
UIButton *MAP_backButton = [[UIButton alloc] init];
MAP_backButton.frame = backBTNFrame;
UIImage *MAP_backButtonIMG = [UIImage imageNamed:#"button_back.png"];
[MAP_backButton setImage:MAP_backButtonIMG forState:UIControlStateNormal];
MAP_backButton.backgroundColor = [UIColor clearColor];
[self addSubview:MAP_backButton];
[MAP_backButton release];
[MAP_backButton addTarget:del.switchVC
action:#selector(gotoMapAndListChooser)
forControlEvents:UIControlEventTouchUpInside];
mapScrollView.multipleTouchEnabled = YES;
}
return self;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return mapImageView;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
if(exScreenEnabled==1){
CGPoint p = mapScrollView.contentOffset;
mapImageViewEx.frame = CGRectMake((p.x*-1), (p.y*-1), mapImageView.frame.size.width, mapImageView.frame.size.height);
}
}
- (void)scrollViewDidScroll:(UIScrollView *)inscrollView{
if(exScreenEnabled==1 && toggleScroll==1){
CGPoint p = mapScrollView.contentOffset;
mapImageViewEx.frame = CGRectMake((p.x*-1), (p.y*-1), mapImageView.frame.size.width, mapImageView.frame.size.height);
}
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)theScrollView withView:(UIView *)view{
NSLog(#"BEGIN ZOOMING");
toggleScroll=0;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)theScrollView withView:(UIView *)view atScale:(float)scale{
NSLog(#"END ZOOMING");
toggleScroll=1;
}
- (void)dealloc {
[mapScrollView release];
[mapImageView release];
[map_List release];
[super dealloc];
}
#end
I pressed the space bar (4) times for code, and NOPE doesn't work stack overflow still broken. :)