I just saw Facebook's new paper app that makes images move based on the parallax effect. So it zoom's the image to full screen and when you tilt the screen, it scrolls the image to the side you tilted. I have been able to add the parallax effect like apple has it, but not like how facebook has it. Does anyone have any ideas how they did this. Here is the basic code I was using for parallax:
UIInterpolatingMotionEffect *interpolationHorizontal = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:#"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
interpolationHorizontal.minimumRelativeValue = #-10.0;
interpolationHorizontal.maximumRelativeValue = #10.0;
UIInterpolatingMotionEffect *interpolationVertical = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:#"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
interpolationVertical.minimumRelativeValue = #-10.0;
interpolationVertical.maximumRelativeValue = #10.0;
[self.backgroundView addMotionEffect:interpolationHorizontal];
[self.backgroundView addMotionEffect:interpolationVertical];
Update:
Just found a very nice 3rd party library for achieving this, it's called CRMotionView, it works very smooth and you can modify a lot of things.
here is the github link: https://github.com/chroman/CRMotionView
==================================================================================
i was thinking the same parallax when i first saw Facebook paper app. but after play with my code for a little bit, i don't think parallax is what we looking for. I could be wrong, but i went to do it all from the base, gyro motion manager. Here is my sample code:
//import the motion manager frame work first
#import <CoreMotion/CoreMotion.h>
//then need to add a motionManager
#property (strong, nonatomic) CMMotionManager *motionManager;
//you can paste all those codes in view did load
//i added a scroll view on the view controller nib file
self.mainScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
//we don't want it to bounce at each end of the image
self.mainScrollView.bounces = NO;
//and we don't want to allow user scrolling in this case
self.mainScrollView.userInteractionEnabled = NO;
//set up the image view
UIImage *image= [UIImage imageNamed:#"YOUR_IMAGE_NAME"];
UIImageView *movingImageView = [[UIImageView alloc]initWithImage:image];
[self.mainScrollView addSubview:movingImageView];
//set up the content size based on the image size
//in facebook paper case, vertical rotation doesn't do anything
//so we dont have to set up the content size height
self.mainScrollView.contentSize = CGSizeMake(movingImageView.frame.size.width, self.mainScrollView.frame.size.height);
//center the image at intial
self.mainScrollView.contentOffset = CGPointMake((self.mainScrollView.contentSize.width - self.view.frame.size.width) / 2, 0);
//inital the motionManager and detec the Gyroscrope for every 1/60 second
//the interval may not need to be that fast
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.gyroUpdateInterval = 1/60;
//this is how fast the image should move when rotate the device, the larger the number, the less the roation required.
CGFloat motionMovingRate = 4;
//get the max and min offset x value
int maxXOffset = self.mainScrollView.contentSize.width - self.mainScrollView.frame.size.width;
int minXOffset = 0;
[self.motionManager startGyroUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMGyroData *gyroData, NSError *error) {
//since our hands are not prefectly steady
//so it will always have small rotation rate between 0.01 - 0.05
//i am ignoring if the rotation rate is less then 0.1
//if you want this to be more sensitive, lower the value here
if (fabs(gyroData.rotationRate.y) >= 0.1) {
CGFloat targetX = self.mainScrollView.contentOffset.x - gyroData.rotationRate.y * motionMovingRate;
//check if the target x is less than min or larger than max
//if do, use min or max
if(targetX > maxXOffset)
targetX = maxXOffset;
else if (targetX < minXOffset)
targetX = minXOffset;
//set up the content off
self.mainScrollView.contentOffset = CGPointMake(targetX, 0);
}
}];
I tested this on my device, worked pretty similar like facebook new app.
However, this is just an example code i wrote in half hour, may not be 100% accurate, but hope this would give you some ideas.
Related
I want to display some images in a scroll view, but I am facing some issues.
Here is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
myObject = [[NSMutableArray alloc] init];
[myObject addObject:#"tut_5.jpg"];
[myObject addObject:#"tut_2.jpg"];
[myObject addObject:#"tut_3.jpg"];
[myObject addObject:#"tut_4.jpg"];
pageControlBeingUsed = NO;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHight = screenRect.size.height;
for (int i = 0; i < [myObject count]; i++) {
CGRect frame;
frame.origin.x = self.takeTourScrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.takeTourScrollView.frame.size;
NSString *val = [myObject objectAtIndex:i];
UIImage* theImage = [UIImage imageNamed:val];
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
img.image = theImage;
[self.takeTourScrollView addSubview:img];
}
The first first image seems to be ok.
Then when I swipe left I am getting a blank screen
I swipe left again and then I see my second picture. And it goes like that for all the 4 images.
Any ideas what am I doing wrong ?
There are system components that will give you what you want with much less work and a more refined user experience. Using a UICollectionView is one possibility, as mentioned by Vive in her answer. My suggestion would be a UIPageViewController. There is a sample app called PhotoScroller from Apple that shows how to implement a UI very much like what you describe. Do a search in the Xcode docs for "PhotoScroller" to find it.
I'd advise to use UITableView/UICollectionView for such behaviour. You can set the image in each cell and they'll be reused - it will be much better in terms of memory management.
The tableView will by the way place all elements in proper places (you just need to define the height of the cell or the layout).
It will also properly resize on events (eg phone rotation).
Also, you should try to avoid hardcoding the sizes:
CGRectMake(screenWidth*i,0,185 ,284)
You will fail in case of smaller / bigger devices. It'll be a great pain to maintain the code after some time.
-- edit --
After #Duncan C posted his answer, I've noticed you're looking for a paging system. You can go with building your own solution either on UIPageViewController or on UICollectionView. However you can also use third party libraries, I really enjoy this one: https://www.cocoacontrols.com/controls/bwwalkthrough. It has a support of different animations and does a ton of stuff for you :).
you already set the x position of uiscrollview. do not need to set the x postion of UIImageView.Because you used imageview as a subview of uiimagescrollview.
change this line to
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
with
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,185 ,284)];
I have a gallery view that I use to, surprise, view images. :) I wanted it to be very similar to the standard iOS photo app with the same basic functionality: scrolling through images that are zoomable. To do this, I use a regular scroll view which I then populate with other scroll views that contain the images. The basic idea is something like this:
And, I do the populating the following way:
for (int i = 0; i < [imageGalleryArray count]; i++)
{
UIScrollView *imageContainer = [[UIScrollView alloc] initWithFrame:CGRectMake((windowSize.width * i), 0.0f, windowSize.width, windowSize.height)];
imageContainer.contentSize = CGSizeMake(windowSize.width, windowSize.height);
imageContainer.showsHorizontalScrollIndicator = NO;
imageContainer.showsVerticalScrollIndicator = NO;
imageContainer.bouncesZoom = YES;
imageContainer.delegate = self;
imageContainer.minimumZoomScale = 1.0f;
imageContainer.maximumZoomScale = 3.0f;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, windowSize.width, windowSize.height)];
imageView.image = [[imageGalleryArray objectAtIndex:i] objectForKey:#"image"];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.tag = IMAGEZOOMVIEW;
imageView.opaque = YES;
[imageContainer addSubview:imageView];
[galleryScrollView addSubview:imageContainer];
// Add it to array for proper removal later
[contentScrollViewSubviewList addObject:imageContainer];
}
Quite simple and it works fine. The only problem arises when I am zoomed into an image and want to scroll to another. The expected behavior in this case would be to set the zoom level of all images back to their original size. I do this in the scrollViewDidEndDecelerating delegate method like so:
if (scrollView.tag == GALLERYSCROLLVIEW)
{
for (int i = 0; i < [contentScrollViewSubviewList count]; i++)
{
[[contentScrollViewSubviewList objectAtIndex:i] setZoomScale:1.0f animated:YES];
}
}
Unfortunately, it does not work (or rather not as intended). I did some poking around and found out that the image does indeed animate back to its original size when it is the active slide. To elaborate: if I zoom into an image and scroll to another, the image stays zoomed in. When I scroll back to it, that is when it zooms back to its original size. I, however, need the image to scale back as soon as I move away from it ().
just like in the iOS image viewer).
Frankly, I do not understand the whole zoom mechanic enough to find out how to do this properly, and the UIScrollView documentation is of no help either. Could someone show me how to solve my problem?
I start out with an imageView.image (a photo).
I submit (POST) the imageView.image to remote service (Microsoft face detection) for processing.
Remote service returns JSON of CGRect's for each detected face on the image.
I feed JSON into my UIView to draw the rectangles. I initiate my UIView with a frame of {0, 0, imageView.image.size.width, imageView.image.size.height}. <-- my thinking, a frame equivalent to the size of the imageView.image
Add my UIView as a subview of self.imageView OR self.view (tried both)
End Result:
Rectangles are drawn but they do not appear correctly on the imageView.image. That is, the CGRects generated for each of the faces are supposed to be relative to the image's coordinate space, as returned by the remote service but they appear off once I add my custom view.
I believe I may have a scaling issue of some sort as, if I divide each value in the CGRects / 2 (as a test) I can get an approximation but still off. The microsoft documentation states the detected faces are returned with rectangles indicating the location of faces in the image in Pixels. Yet, aren't they being treated as points when drawing my path?
Also, shouldn't I be initiating my view with a frame equivalent to the imageView.image's frame so that the view matches an identical coordinate space as the submitted image?
Here is a screenshot example of what it looks like if i try to scale down each CGRect by dividing them by 2.
I am new to iOS and broke away from the books to work on this as a self exercise. I can provide more code as needed. Thanks in advance for your insight!
EDIT 1
I add a subview for each rectangle as I iterate over an array of face attributes which include the rectangle for each face via the following method, which gets called during (void)viewDidAppear:(BOOL)animated
- (void)buildFaceRects {
// build an array of CGRect dicts off of JSON returned from analized image
NSMutableArray *array = [self analizeImage:self.imageView.image];
// enumerate over array using block - each obj in array represents one face
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// build dictionary of rects and attributes for the face
NSDictionary *json = [NSDictionary dictionaryWithObjectsAndKeys:obj[#"attributes"], #"attributes", obj[#"faceId"], #"faceId", obj[#"faceRectangle"], #"faceRectangle", nil];
// initiate face model object with dictionary
ZGCFace *face = [[ZGCFace alloc] initWithJSON:json];
NSLog(#"%#", face.faceId);
NSLog(#"%d", face.age);
NSLog(#"%#", face.gender);
NSLog(#"%f", face.faceRect.origin.x);
NSLog(#"%f", face.faceRect.origin.y);
NSLog(#"%f", face.faceRect.size.height);
NSLog(#"%f", face.faceRect.size.width);
// define frame for subview containing face rectangle
CGRect imageRect = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
// initiate rectange subview with face info
ZGCFaceRectView *faceRect = [[ZGCFaceRectView alloc] initWithFace:face frame:imageRect];
// add view as subview of imageview (?)
[self.imageView addSubview:faceRect];
}];
}
EDIT 2:
/* Image info */
UIImageView *iv = self.imageView;
UIImage *img = iv.image;
CGImageRef CGimg = img.CGImage;
// Bitmap dimensions [pixels]
NSUInteger imgWidth = CGImageGetWidth(CGimg);
NSUInteger imgHeight = CGImageGetHeight(CGimg);
NSLog(#"Image dimensions: %lux%lu", imgWidth, imgHeight);
// Image size pixels (size * scale)
CGSize imgSizeInPixels = CGSizeMake(img.size.width * img.scale, img.size.height * img.scale);
NSLog(#"image size in Pixels: %fx%f", imgSizeInPixels.width, imgSizeInPixels.height);
// Image size points
CGSize imgSizeInPoints = img.size;
NSLog(#"image size in Points: %fx%f", imgSizeInPoints.width, imgSizeInPoints.height);
// Calculate Image frame (within imgview) with a contentMode of UIViewContentModeScaleAspectFit
CGFloat imgScale = fminf(CGRectGetWidth(iv.bounds)/imgSizeInPoints.width, CGRectGetHeight(iv.bounds)/imgSizeInPoints.height);
CGSize scaledImgSize = CGSizeMake(imgSizeInPoints.width * imgScale, imgSizeInPoints.height * imgScale);
CGRect imgFrame = CGRectMake(roundf(0.5f*(CGRectGetWidth(iv.bounds)-scaledImgSize.width)), roundf(0.5f*(CGRectGetHeight(iv.bounds)-scaledImgSize.height)), roundf(scaledImgSize.width), roundf(scaledImgSize.height));
// initiate rectange subview with face info
ZGCFaceRectView *faceRect = [[ZGCFaceRectView alloc] initWithFace:face frame:imgFrame];
// add view as subview of image view
[iv addSubview:faceRect];
}];
We've got several problems :
Microsoft returns pixel and iOS uses points. The difference between them is just about screen dimension. For instance on an iPhone 5 : 1 pt = 2 px and on an 3GS 1px = 1 pt. Look at the iOS documentation for more informations.
The frame of your UIImageView is not the image frame. When Microsofts returns the frame of a face, it returns it in the frame of the image and not in the frame of the UIImageView. So we've got a problem of coordinates system.
Be careful about time if you use Autolayout. The frame of a view set by constraints is not the same when ViewDidLoad: is called than when you see it on the screen.
Solution :
I'm just a read-only Objective C developer so I can't give you code. I could in Swift but it's not necessary.
Convert pixels into points. That's easy : use ratio.
Define the frame of a face using what you did. Then you have to move the coordinates you determined from the image frame coordinates system to the UIImageView coordinates system. That's less easy. It depends on the contentMode of your UIImageView. But I quickly find informations about it on the Internet.
If you use AutoLayout, add the frame of the face when AutoLayout finishes to calculate the layouts. So when ViewDidLayoutSubview: is called.
Or, that's better, use constraints to set your frame in the UIImageView.
I hope to be clear enough.
Some links :
iOS Drawing Concepts
Displayed Image Frame In UIImageView
Please, help me study objective-c!
My program takes a screenshot of whole UIWebView content, saves it, and supposed to display it.
It works fine, until it meets a very long page. Seems like the height of a page is an issue, since it displays 5 Mb screenshots just fine, as long as they are not too long (don't have to much height), however 1Mb but extremely long screenshots do not display in the UIImageView at all. It displays the UIImageView's background and that's it.
My code, attempts to resize the page to be maximum 2000 in height, and minimum 75% of the whole screen size. Aspect ratio is secondary. However, the image is still missing:
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat divider = 2;
CGFloat imageDisplayLimit = 2000;
CGFloat width = _image.size.width;
CGFloat height = _image.size.height;
//determine the leading parameter (just in case of a fat-S image)
if (width > imageDisplayLimit || height > imageDisplayLimit) {
if (width > height) {
divider = width / imageDisplayLimit;
} else {
divider = height / imageDisplayLimit;
}
}
//don't let it get too fat
CGFloat minimumWidth = self.view.frame.size.width / 1.5;
if (width / divider < minimumWidth) {
width = minimumWidth;
} else {
width /= divider;
}
//don't let it get too long
CGFloat minimumHeight = self.view.frame.size.height / 1.5;
if (height / divider < minimumHeight) {
height = minimumHeight;
} else {
height /= divider;
}
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.frame = CGRectMake(0, 0, width, height);
//now just to make it obvious - red background
_imageView.backgroundColor = [UIColor redColor];
_imageView.frame = CGRectMake(0, 0, _image.size.width / divider, _image.size.height / divider);
_imageView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin);
_imageView.contentMode = UIViewContentModeScaleAspectFill;
[_scrollView addSubview:_imageView];
_scrollView.contentSize = _imageView.bounds.size;
_scrollView.delegate = self;
//just to make scroll visible during debug
_scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
...
At this point nothing shows, but the red background on a scrollable view.
I'm studying objective-c and don't know A LOT, but I was trying to find a solution for 2 days now. Please, save me!
My guess is aspect fill or fit doesn't do anything just because they don't actually change the image - just a display. What I really should be using (IMHO) is the UIGraphicsBeginImageContext. But I simply don't know how to make it shrink to max 2000 px. I am able to cut it by using
UIGraphicsBeginImageContext(someSizeWith2000Height)
[originalImage drawInRect:CGRectMake(resized_x, resized_y, resized_width, resized_height)];
UIImage* resized_image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
or something like that, but I don't wanna cut it - just shrink (or stretch if too short).
Any ideas? I've run out of those.
Well, since stackoverflow's system is so great, it drops questions between the desks and none can find them, I had to give up on this problem, and the only solution I could come up with is replace UIImageView with UIWebView as an image-displaying view. It makes the image displayed with TERRIBLE quality, but at least it is displayed.
Please, if anyone finds this question by chance and can help.... help! :)
I was going through the SpriteKit documentation by Apple and came across a really useful feature that I could use when programming my UI. The problem is I can't get it to work.
Please see this page and scroll down to "Resizing a Sprite" - Apple Docs
I have literally copied the image dimensions and used the same code incase I was doing something wrong. But I always end up with a stretched looking image rather than the correct "end caps" staying the same scale.
I am referring to this code:
SKSpriteNode *button = [SKSpriteNode spriteWithImageNamed:#"stretchable_button.png"];
button.centerRect = CGRectMake(12.0/28.0,12.0/28.0,4.0/28.0,4.0/28.0);
What am I doing wrong? Is there a step I have missed?
EDIT:
Here is the code I have been using. I stripped it of my button class and tried to use it with an SKSPriteNode but still the problem persists. I also changed the image just to make sure it wasnt that. The image im using is a 32x32 at normal size.
SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:#"Button.png"];
[self addChild:button];
button.position = ccp(200, 200);
button.size = CGSizeMake(128, 64);
button.centerRect = CGRectMake(9/32, 9/32, 14/32, 14/32);
The .centerRect property works as documented if you adjust the sprites .scale property.
Try:
SKTexture *texture = [SKTexture textureWithImageNamed:#"Button.png"];
SKSpriteNode *button = [[SKSpriteNode alloc] initWithTexture:texture];
button.centerRect = CGRectMake(9/32, 9/32, 14/32, 14/32);
[self addChild:button];
button.xScale = 128.0/texture.size.width;
button.yScale = 64.0/texture.size.height;
9/32 is integer division, so the result passed to CGRectMake is zero. Ditto the other three parameters. If you use floating point literals like the example you cite, you might get better results.
Here's a refresh of how exactly this works. By the way, my image size width is 48 pixels and height is 52 pixels, but this doesn't matter at all. Any image can be used:
SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:#"Button.png"];
//(x, y, width, height). First two values are the four corners of the image that you DON'T want touched/resized (They will just be moved).
//The second two values represent how much of images width & height you want cut out & used as stretching material. Cut out happens from the center of the image.
button.centerRect = CGRectMake(20/button1.frame.size.width, 20/button1.frame.size.height, 5/button1.frame.size.width, 15/button1.frame.size.height);
button.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2); //Positions sprite in the middle of the screen.
button.xScale = 4; //Resizes width (This is all I needed).
//button.yScale = 2; //Resizes height (Commented out because I didn't need this. You can uncomment if the button needs to be higher).
[self addChild:button];
Read the section called "Resizing a Sprite" in this document: https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Sprites/Sprites.html#//apple_ref/doc/uid/TP40013043-CH9-SW10
'Figure 2-4 A stretchable button texture' demonstrates how the (x, y, width, height) works.
Based on rwr's answer here is a working init method for a SKSpriteNode. I use this in my own game. Basically you make insets of 10px all around the the output image. And then call it like this:
[[HudBoxScalable alloc] initWithTexture:[atlas textureNamed:#"hud_box_9grid.png"] inset:10 size:CGSizeMake(300, 100) delegate:(id<HudBoxDelegate>)clickedObject];
-(id) initWithTexture:(SKTexture *)texture inset:(float)inset size:(CGSize)size {
if (self=[super initWithTexture:texture]) {
self.centerRect = CGRectMake(inset/texture.size.width,inset/texture.size.height,(texture.size.width-inset*2)/texture.size.width,(texture.size.height-inset*2)/texture.size.height);
self.xScale = size.width/texture.size.width;
self.yScale = size.height/texture.size.height;
}
return self;
}