iOS: ImageView filled with a picture - ios

I have a table that contains the path to the picture, saved on user's library. Then, I pass this path to a View that contains just a imageView. I want to fills this ImageView with the picture. Like WhatsApp (when you click on a profile's picture). But, my picture it's always cropped or distorted. I tryed different ways to do this, but I didn't find the best way:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.translucent = NO;
UIImage *picture = [UIImage imageWithContentsOfFile: self.picturePath]; //I passed this path from the previous View
UIImageView* imageView = [[UIImageView alloc] initWithImage:picture];
CGRect screenRect = [[UIScreen mainScreen] bounds];
imageView.frame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:imageView];
}
Original (I want something like it)
My app

If your image is cut , the reason is you are using a higher resolution image in a smaller container and instructed your imageview to fill , using this line imageView.contentMode = UIViewContentModeScaleAspectFill;
Change it to imageView.contentMode = UIViewContentModeScaleAspectFit;

I think #whitewolf09 is right and his method will solve your problem. But i suggest you to look into MGImageUtilities that will be very useful for different cases where you can crop images maintaining aspect ratio to fit inside your image view's frame.
Just #import "UIImage+ProportionalFill.h"
UIImage *image = [[UIImage imageWithContentsOfFile:filePath] imageScaledToFitSize:imageView.frame.size];
That's the very useful category for image resizing and may help you in future.

I think the reason it is being clipped is that you are creating the image view with a picture THEN setting the frame and probably the picture is bigger than the frame so it is clipping it. Also try changing the aspect to: 'UIViewContentModeScaleAspectFit' Try this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.translucent = NO;
UIImage *picture = [UIImage imageWithContentsOfFile:self.picturePath]; //I passed this path from the previous View
UIImageView* imageView = [[UIImageView alloc] initWithRect:CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);];
CGRect screenRect = [[UIScreen mainScreen] bounds];
imageView.image = picture;
imageView.contentMode = UIViewContentModeCenter;
[self.view addSubview:imageView];
}

Related

UIViewContentModeScaleAspectFit doesn't work

I try to scale my image and i want use Aspect Fit. But it doesn't work
solutionImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"bg_solution#2x.png"]];
// optional:
solutionImageView.contentMode = UIViewContentModeScaleAspectFit; // content mode
solutionImageView.center = CGPointMake((currentWidth)/2, currentHeight - (currentHeight/3.5));
[self.view addSubview:solutionImageView];
As arunit21 said in his comment, when you create an UIImageView with the initWithImage method, the size of frame of the view is calculated with image size. So your image view is centered but bigger than you window.
You can do
solutionImageView = [[UIImageView alloc] initWithFrame:yourFrame];
solutionImageView.image = [UIImage imageNamed:#"bg_solution"];
solutionImageView.contentMode = UIViewContentModeScaleAspectFit; // content mode
solutionImageView.center = CGPointMake((currentWidth)/2, currentHeight - (currentHeight/3.5));
[self.view addSubview:solutionImageView];
You can also just set your new frame after your initialization to set the correct size.
The #2x.pngis not needed in [UIImage imageNamed:#"bg_solution"]. With this method, the system will check if the screen is retina and look for the #2ximage if it exists and take the normal one otherwise.

iOS: Make image width slightly smaller than screen width

I'm having an issue where my image is too big. I need it to be slightly less than what the screen width is.
Here's my controller:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageName = #"goldencoaster";
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"table"]]];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%#", self.imageName]];
CGRect bounds;
bounds.origin = CGPointZero;
bounds.size = [[UIScreen mainScreen] bounds].size;
self.coasterImage.bounds = bounds;
self.coasterImage.image = image;
}
However, this returns this when I run the simulator:
How would I get the image to show up slightly smaller than the screen width?
====================================================================
UPDATE
So I took out auto layout as suggested, and updated my controller to look like this:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageName = #"goldencoaster";
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"table"]]];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%#", self.imageName]];
CGRect screen = [[UIScreen mainScreen] bounds];
CGRect bounds;
bounds.origin.x = screen.origin.x + 10;
bounds.origin.y = screen.origin.y + 10;
bounds.size.width = screen.size.width - 100;
self.coasterImage.frame = bounds;
self.coasterImage.image = image;
}
However, now my image doesn't show up at all?? Only the background (image with name "table") shows up, but not the goldencoaster.
Try this
- (void)viewDidLoad {
[super viewDidLoad];
self.imageName = #"goldencoaster";
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"table"]]];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%#", self.imageName]];
CGRect bounds;
bounds.origin = CGPointZero;
bounds.size = [[UIScreen mainScreen] bounds].size;
self.coasterImage.bounds = bounds;
self.coasterImage.image = image;
self.coasterImage.frame = CGRectMake(20, 0, self.view.frame.size.width-40, self.view.frame.size.height);
self.coasterImage.center = self.coasterImage.superview.center;
}
Swift 3.1
override func viewDidLoad() {
super.viewDidLoad()
imageName = "goldencoaster"
view.backgroundColor = UIColor(patternImage: UIImage(named: "table")!)
let image = UIImage(named: imageName)
var bounds = CGRect()
bounds.origin = CGPoint.zero
bounds.size = (UIScreen.main.bounds).size
coasterImage.bounds = bounds
coasterImage.image = image
coasterImage.frame = CGRect(x: CGFloat(20), y: 0, width: self.view.frame.size.width - CGFloat(40), height: self.view.frame.size.height)
coasterImage.center = (coasterImage.superview?.center)!
}
you can do it with contentMode like
self.coasterImage.contentMode = UIViewContentModeScaleAspectFit;
here are the different contentMode check it from here
UIViewContentModeScaleToFill
UIViewContentModeScaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill // contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter // contents remain same size. positioned adjusted.
UIViewContentModeTop
UIViewContentModeBottom
UIViewContentModeLeft
UIViewContentModeRight
UIViewContentModeTopLeft
UIViewContentModeTopRight
UIViewContentModeBottomLeft
UIViewContentModeBottomRight
Two words: Auto Layout
You want your UI to adapt to different devices, and orientations.
Auto Layout and size classes are designed to handle those needs.
Update:
You're checking screen size and setting bounds. That suggests you're trying to size the view instead of letting Auto Layout constrain it. Auto Layout takes the place of setting frame or bounds. You don't want to mix the two.
If you weren't using autolayout, you will need to edit the image frame. For example if you want to reduce the size in 10 pixels:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageName = #"goldencoaster";
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"table"]]];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%#", self.imageName]];
CGRect screen = [[UIScreen mainScreen] bounds];
CGRect bounds = CGRectMake(screen.origin.x+10,
screen.origin.y+10,
screen.size.width-20,
screen.size.height-20);
self.coasterImage.center = self.coasterImage.superview.center;
self.coasterImage.frame = bounds;
self.coasterImage.image = image;
}

Stopping UIScrollView at specific place while scrolling with pagingEnabled

I have the following code to create a scroll view with additional area at the beginning and the end of the images (50 points).
UIScrollView* scroll = [[UIScrollView alloc] initWithFrame: CGRectMake(0,0,200,100)];
scroll.contentSize = CGSizeMake(400,100);
UIImageView* img1 = [[UIImageView alloc] initWithFrame: CGRectMake(50,0,100,100);
UIImageView* img2 = [[UIImageView alloc] initWithFrame: CGRectMake(150,0,100,100);
UIImageView* img3 = [[UIImageView alloc] initWithFrame: CGRectMake(250,0,100,100);
//Adding images to ImageViews
scroll.pagingEnabled = YES;
[scroll addSubView:img1];
[scroll addSubView:img2];
[scroll addSubView:img3];
The first time I see the view, I will see the additional area on the left (0-50), then the first image (50-150) and then half of the second image (150-200).
When I swipe left, I want to see half of the first image on the right, the second image at the center, and half of the third image on the right.
When I swipe left again, I want to see the third image at center, with half of the second image on the left, and the additional area on the right.
Can it be possible?
It's possible as long as you define everything correctly. Make sure that the assigned content size is equal to the overall size that you wish to scroll through. Make sure that each page size is equal to the scroll view's frame. You can set the clipsToBounds to NO if the frame clips your subviews.
You can do this by adjusting the contentSize of UIScrollView
- (void)addImagesToScrollView{
//An offset from where imageViewStarts
CGFloat xOffset = 50.0f;
CGRect imageViewFrame = CGRectMake(xOffset, 0.0f, 100.0f, 100.0f);
for (NSString *imageName in #[#"image1.jpg",#"image2.jpg",#"image3.jpg"])
{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:imageViewFrame];
UIImage *image = [UIImage imageNamed:imageName];
imageView.image = image;
[self.scrollView addSubview:imageView];
imageViewFrame.origin.x+=imageViewFrame.size.width;
}
CGSize contentSize = self.scrollView.frame.size;
//Content size is calculate from the imageViewFrame and an offset is added to it
contentSize.width = imageViewFrame.origin.x+xOffset;
[self.scrollView setContentSize:contentSize];
}
Source Code
You can scroll to a particular place in the scrollview using the following code
[YOURSCROLLVIEW setContentOffset:CGPointMake(x, y) animated:YES];

Graphical glitch in UIScrollView when autorotating device

I have an application which has a fullscreen UIScrollView, and within it there are seven images. The images are also meant to be full screen, and the scroll view is set to enable pagination.
I have a method which either creates or moves the image views:
-(void)rebuildImageView{
// set up images
float screenW = self.view.bounds.size.width;
float screenH = self.view.bounds.size.height;
int numImgs = self.soundNames.count;
self.mainScrollView.contentSize = CGSizeMake(screenW * numImgs, screenH);
for(int i=0; i<numImgs; i++){
UIImageView* imageView = (UIImageView*)[self.mainScrollView viewWithTag:i+100];
if(imageView == nil){
imageView = [[UIImageView alloc] init];
imageView.tag = i+100;
[self.mainScrollView addSubview:imageView];
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"image%d.jpg",i]];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
[imageView release];
}
imageView.frame = CGRectMake(i * screenW, 0, screenW, screenH);
}
// scroll to the current one
[self.mainScrollView scrollRectToVisible:CGRectMake(self.currentSound*screenW, 0, screenW, screenH) animated:YES];
}
I also have this on the view controller:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
[UIView animateWithDuration:duration animations:^{
[self rebuildImageView];
}];
}
This code works fine when I autorotate while image 0 is being shown, but when I'm on image 7, you can briefly see most of image 6 when rotating. This video shows what's happening:
http://www.youtube.com/watch?v=1O3jOcTgVP8
Is there a better method I should use to reconfigure the scroll view and images when rotating the device?
Any frame changes put in the willAnimateRotationToInterfaceOrientation:duration method should automatically animate. So you could try removing it from the block?
Personally, I've had a lot more luck with this type of thing subclassing UIScrollView and putting the equivalent layout subview frame code in an override of the layoutSubviews method (don't forget to call super or you might end up with misplaced scroll bars).

Creating a custom progress bar with images

Pretty much what I am trying to do, is create the following image:
So this is a progress bar, which will show how many votes the client get in that option. How can I do that? I was wondering if I can use a mask (as I would in flex), but all the masking implementations that I found on the web are doing masks for UIImages, and not for UIImageView. I cannot do the mask in the UIImage, because the two images have the same dimensions. I have to use the X and Y of the images to crop them?! So, any suggestions?
Here are the two images that I have to create that progress bar:
Cheers.
you want to get rid of all of the same bit in the middle of each image.
then do something like:
- (void)viewDidLoad
{
[super viewDidLoad];
[self addProgressBarInFrame:CGRectMake(20.f, 20.f, 280.f, 50.f) withProgress:.9f];
[self addProgressBarInFrame:CGRectMake(20.f, 100.f, 200.f, 25.f) withProgress:.1f];
}
-(void)addProgressBarInFrame:(CGRect)frame withProgress:(CGFloat)progress
{
float widthOfJaggedBit = 4.0f;
UIImage * imageA= [[UIImage imageNamed:#"imageA"] stretchableImageWithLeftCapWidth:widthOfJaggedBit topCapHeight:0.0f];
UIImage * imageB= [[UIImage imageNamed:#"imageB"] stretchableImageWithLeftCapWidth:widthOfJaggedBit topCapHeight:0.0f];
UIView * progressBar = [[UIView alloc] initWithFrame:frame];
progressBar.backgroundColor = [UIColor whiteColor];
UIImageView * imageViewA = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, frame.size.width*progress, frame.size.height)];
UIImageView * imageViewB = [[UIImageView alloc] initWithFrame:CGRectMake(frame.size.width*progress, 0.f, frame.size.width - (frame.size.width*progress), frame.size.height)];
imageViewA.image = imageA;
imageViewB.image = imageB;
// imageViewA.contentStretch = CGRectMake(widthOfJaggedBit, 0, imageA.size.width - 2*widthOfJaggedBit, imageA.size.height) ;
// imageViewB.contentStretch = CGRectMake(widthOfJaggedBit, 0, imageB.size.width - 2*widthOfJaggedBit, imageB.size.height) ;
[self.view addSubview:progressBar];
[progressBar addSubview:imageViewA];
[progressBar addSubview:imageViewB];
}
Grady Player's answer is great. Just a small note, for anyone that uses this. I tried to update the frames of the two UIImageView's to update the "progress". I tried to force an update with "setNeedsDisplay", but to no avail. (sizeToFit caused problems too).
Anyway, the only way I figured out how to update the progress of an existing progress bar was to call "setFrame:CGRectMake" with my new dimensions.

Resources