I am a beginner in iOS development and stuck at the following problem.
In .xib file I have button and imageview as displayed in following image.
Now I did the following to show image in image view and set content mode in .m file.
UIImage *save = UIGraphicsGetImageFromCurrentImageContext();
self.ivCard.image = save;
self.ivCard.contentMode = UIViewContentModeScaleAspectFit;
self.ivCard.clipsToBounds = YES;
Now the result looks like the following image.
The original image has resolution of 2000x1000, here it is
The image is automatically cropped from the right side, it should be fit with image view.
Pretty sure you didn't add constraints to the ImageView, the ImageView size it's not the same as the device size.
Add constraints from the ImageView to the borders in the Interface Builder, and it will work.
Check: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraints/WorkingwithConstraints.html
There are 2 ways to achieve it.
You can either go for constraints and add constraints to your image view either from your .xib file or prgrammatically as shown below:
// align ivCard from the left and right
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[ivCard]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(ivCard)]];
// align ivCard from the top and bottom
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-20-[ivCard]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(ivCard)]];
You can directly set frame for image view using this code:
CGFloat btnHeight = 20; // Your back button height from xib
self.ivCard.frame = CGRectMake(0, btnHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - btnHeight);
Related
I'm facing a really weird problem with UIImageView, I was trying to set an image - which created by take the screenshot of the current view - to an ImageView with content mode is UIViewContentModeScaleAspectFit.
It worked fine when I set the image by the interface builder in the xib file or when I set the image created by [UIImage imageNamed:]. They both worked fine with UIViewContentModeScaleAspectFit.
But when I take the snap shot of a view and set the image to the image view, the image did not fit to the UIImageView. I've tried all the solutions I found on here like .ClipsToBound = YES but they didn't work at all. I'm really confused by now.
Here's the code when I take the screen shot and create the UIImage:
- (UIImage *)screenshotWithRect:(CGRect)captureRect
{
CGFloat scale = [[UIScreen mainScreen] scale];
UIImage *screenshot;
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, scale);
CGContextClipToRect (UIGraphicsGetCurrentContext(),captureRect);
{
if(UIGraphicsGetCurrentContext() == nil)
{
NSLog(#"UIGraphicsGetCurrentContext is nil. You may have a UIView (%#) with no really frame (%#)", [self class], NSStringFromCGRect(self.frame));
}
else
{
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
screenshot = UIGraphicsGetImageFromCurrentImageContext();
}
}
UIGraphicsEndImageContext();
return screenshot;
}
And when I set the image to the image view
UIImage* snap = [[UIImage alloc] init];
// start snap shot
UIView* superView = [self.view superview];
CGRect cutRect = [superView convertRect:self.cutView.frame fromView:_viewToCut];
snap = [superView screenshotWithRect:cutRect];
[self.view addSubview:self.editCutFrameView];
// end snap shot -> show edit view
[self.editCutFrameView setImage:snap];
Here's a picture compare the 2 results:
Many thanks for your help.
UPDATE: As #Saheb Roy mentioned about the size, I checked the image size and it's about 400x500px and the thumbnail.png's size is 512x512px so I think it's not about the size of the image.
This is because in the second case, the snapshot image is itself exactly that size as you can see. Hence the image is not being stretched or fitted accordingly.
Earlier images are fitting to screen accordingly as the images were bigger than the imageview but with different ratio or same than that of the image.
But the one where it is not fitting to the imageview, the image itself is of that much size, i.e. smaller than that of the imageview, hence it is NOT being fitted to the bounds.
I'm working on an application that will have a picture of guitar fretboard like on a screenshot above. There will be notes displayed in different places of fretboard (represented by red circles- there will be much more of them than on the screenshot).
What kind of solution would you recommend to guarantee that the notes will be displayed in the right places of fretboard (which is just an image) and will not fall apart or distribute unevenly? Remember that the fretboard image will scale, depending on resolution, so notes positions coordinates should change accordingly.
If you're going to use an image that scales with the screen size, then this is one of the few cases where I would probably not use auto layout. I would create an array of doubles that would be the fraction of the distance from the left edge to the center of a particular space between the frets. So for instance, the value at index 3 (for the space where your left most red dot is) would be 0.2707 (36mm/133mm based on your image). You would then set the frame's origin.x value with that fraction times the width of the image.
You want to do all this in code I think and be able to activate based on fret location, string location etc... Use relative offsets for each string and fret from a known point.
This ties into your other question on SO about getting your fret image correct. Unless you can code the image accurately, then coding the note positions accurately is going to be tricky.
IMHO, you can not do this with auto layout, esp taking into account your other question: iOS autolayout - gap between image and top of the screen, despite constraints set
If you already managed to place the imageViews in the right places, you could create an UIView subclass that contains both the image and a label on top of it.
This would be my suggestion:
#interface NoteView()
#property (nonatomic, weak) UILabel *label;
#property (nonatomic, weak) UIImageView *imageView;
#end
#implementation NoteView
-(instancetype)init {
self = [super init];
if (self) {
[self setupContent];
}
return self;
}
- (void)setupContent {
UIImageView *imageView = [[UIImageView alloc] init];
[self addSubview:imageView];
[imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
UILabel *label = [[UILabel alloc] init];
[self addSubview:label];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
// This adds vertical constaints between the view, the label and the imageView
// You can change the values to suit your needds
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[label]-10-[imageView]-0-|" options:0 metrics:nil views:#{ #"label": label, #"imageView": imageView }]];
// This makes the view be as big as the label
// I assumed the labels will be bigger than the images,
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[label]-0-|" options:0 metrics:nil views:#{ #"label": label}]];
// If the images are bigger use these constraints
// [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[label]-0-|" options:0 metrics:nil views:#{ #"label": label}]];
// This msakes sure that the label and the image have the same centers
[self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:imageView attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0]];
[self setLabel:label];
[self setImageView:imageView];
}
// This would be a public configuration method.
- (void)setLabelText:(NSString *)text andImage:(UIImage *)image {
[self.label setText:text];
[self.imageView setImage:image];
}
#end
All you would need to do is place this custom view as you do with the images and if the frame changes call layoutIfNeeded on the custom view so that it layouts both the image and the label correctly.
Hope this helps. Let me know if you have questions.
Please see my answer below, where I have a working solution
I have rewritten the code completely so it is much smaller and neater and achieves the same results.
Update: It looks like the intrinsic content size of the UIImageView is being adjusted when the large image is loaded, which throws its layout and makes it twice the width of device window and scrollview. I will need to figure out how to fix that. The code below made a small change and reduced the width of the UIImageView, but did not allow me to set it to be 100% the width of the window.
[captionImageView setContentCompressionResistancePriority:1 forAxis:UILayoutConstraintAxisHorizontal];
I have the following set up for my views and my problem is that an image inside the UIImageView is pushing the width of its containing view to be wider than the device window.
I have a ViewController that loads and adds subviews in a for loop and everything seems to be working ok there.
Inside these sub views I am trying to use autolayout to achieve the following:
Add a UIImageView and make it the same width as the parent window
Load a UIImage into this and use UIViewContentModeScaleAspectFill to make sure the image loads nice and proportionally.
Load a UITextView beneath all this
Repeat this process in the for loop so they all stack up nicely on top of one another.
I am using a constraint for in the Visual formatting language to try to set the size of the UIImage view to be the width of the parent view, which I want to be the device window width.
If I specify the constraint as follows:
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionImageView(320)]|" options:0 metrics:metrics views:views]];
Then it works ok, but this is not the ideal solution as I want the UIImageView to be flush with the width of the device, and it's bad practice to set a fixed width
If I specify the constraint as follows like this:
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionImageView]|" options:0 metrics:metrics views:views]];
Then the UIImage with a size of let's say 960px will force the parent container view to be that size as well.
I have my custom view content being loaded into a scroll view, and so we have horizontal scrolling which is bad.
Note that I am using a UIView category to specify that view.translatesAutoresizingMaskIntoConstraints is set to NO.
#import "UIView+Autolayout.h"
#implementation UIView (Autolayout)
+(id)autoLayoutView {
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
#end
The code for the custom view is below. Any ideas as to how I can ensure the size of my UIImageView does not stretch beyond the bounds of the device window?
//
// FigCaptionView.m
//
//
// Created by Matthew Finucane on 18/12/2014.
// Copyright (c) 2014 The App. All rights reserved.
//
#import "FigCaptionView.h"
#import "UIView+Autolayout.h"
#interface FigCaptionView(){}
#end
#implementation FigCaptionView
-(id)initWithData:(NSDictionary *)viewData {
if((self = [FigCaptionView autoLayoutView])) {
self.figCaptionData = viewData;
}
return self;
}
-(void)layoutItems {
[self setBackgroundColor:[UIColor redColor]];
/**
* The container view for everything
*/
UIView *containerView = [UIView autoLayoutView];
/**
* Setting up the caption image
*/
UIImageView *captionImageView = [UIImageView autoLayoutView];
[captionImageView setContentMode:UIViewContentModeScaleAspectFill];
/**
* Grabbing the image (not yet the right way to do this)
*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://placekitten.com/960/240"] options:0 error:nil]];
dispatch_async(dispatch_get_main_queue(), ^{
captionImageView.image = image;
});
});
/**
* Setting up the caption image
*/
UITextView *captionTextView = [UITextView autoLayoutView];
[captionTextView setText:#"Sample paragraph text will go in here. Sample paragraph text will go in here. Sample paragraph text will go in here. Sample paragraph text will go in here. Sample paragraph text will go in here.Sample paragraph text will go in here"];
/**
* Adding the container view
*/
[self addSubview:containerView];
[containerView addSubview:captionImageView];
[containerView addSubview:captionTextView];
[captionTextView setBackgroundColor:[UIColor blueColor]];
/**
* Dictionaries for autolayout: views and metrics
*/
NSDictionary *views = NSDictionaryOfVariableBindings(containerView, captionImageView, captionTextView);
NSDictionary *metrics = #{#"imageHeight": #"160.0", #"margin": #"20.0"};
/**
* Setting up the constraints for this view
*/
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[containerView]|" options:0 metrics:metrics views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[containerView]|" options:0 metrics:metrics views:views]];
/**
* Container view constraints
*
* The first constraint is the one that might be causing me trouble.
*/
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionImageView]|" options:0 metrics:metrics views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionTextView]|" options:0 metrics:metrics views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[captionImageView(imageHeight)][captionTextView]|" options:NSLayoutFormatAlignAllLeft metrics:metrics views:views]];
for(UIView *view in self.subviews) {
if([view hasAmbiguousLayout]) {
NSLog(#"OOPS");
NSLog(#"<%#:0x%0x>", view.description, (int)self);
}
}
}
#end
You can handle it in this way.
Assume ViewA's width is equal to the device window 's width.In this case, you can just add a UIView.
And set it up with constraints likes the usual view you had handled above.
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionImageView(ViewA)]|" options:0 metrics:metrics views:views]];
Hope this help.
Edit:
Cause I am not very sure it will work or not in the way that you comment to me. So I just showed the code how I deal with.
1.set up the viewA
_viewA = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
2.Just handle it likes your UIImageView (in this case, captionImageView)
[self.view addSubView:_viewA];
[_viewA setTranslatesAutoresizingMaskIntoConstraints:NO];
3.Add it into NSDictionaryBinding
NSDictionary *dictionary = NSDictionaryOfVariableBindings(_textView, _button, _viewA);
4.Custom the VFL and assign it.
NSString *const KButtonHorizontal = #"|[_button(_viewA)]|";
This is the tech note that explains how to constrain a scroll view: https://developer.apple.com/library/ios/technotes/tn2154/_index.html
A quick and easy way to prevent the scroll view content size from growing is to subclass the scrollview and override -(CGSize)contentSize to return the windows width and whatever super returns for height.
I got this working by Subclassing UIImageView and overriding intrinsicContentSize() to return the screen size... less code ;)
class CustomImageView: UIImageView
{
// - MARK: UIView
override func intrinsicContentSize() -> CGSize
{
// Return current screen size with width adjusted for frame
let width = UIScreen.mainScreen().bounds.width - frame.origin.x
return CGSize(width: width, height: frame.height)
}
}
I would not necessarily call this a definitive answer, but I was able to get it working somewhat the way I wanted to, although the solution I went with might not have been 100%.
-- The answer provided by Henry T Kirk was very useful in describing autolayout with image views. I could not get this working 100% but I would say this is the most correct answer in that it follows best practice.
-- The answer provided by WorldOfWarcraft also works. Creating a new view that stretches to 100% the width of the device window, and setting the constraint of the UIImage based on that will stop it from stretching beyond its bounds.
The solution I went with was to create a new CGRect variable called windowBounds. Extracting the window width from that (windowBounds.size.width), I was able to add this to my metrics, and apply it to the visual formatting string horizontal rule for the imageView, thus correcting the constraint for its superview.
After doing some work to refactor the code for this view, I have come up with a much neater solution that works, and also solves another issue I had with placing a UITextView with variable string content. The code is below.
** FigcaptionView.h **
//
// FigCaptionView.m
// Anna Christoffer
//
// Created by Matthew Finucane on 18/12/2014.
// Copyright (c) 2014 Anna Christoffer. All rights reserved.
//
#import "FigCaptionView.h"
#import "UIView+Autolayout.h"
#interface FigCaptionView(){}
#property (nonatomic, strong) UIImageView *figCaptionImageView;
#property (nonatomic, strong) UITextView *figCaptionTextView;
#end
#implementation FigCaptionView
#synthesize figCaptionImageView;
#synthesize figCaptionTextView;
-(id)initWithData:(NSDictionary *)viewData {
if((self = [FigCaptionView autoLayoutView])) {
self.figCaptionData = viewData;
}
return self;
}
-(void)loadImage:(NSString *)imageURLPath {
//TODO
}
-(void)addContentViews {
[super layoutSubviews];
/**
* Set up and add the subviews to display the content
*/
self.figCaptionImageView = [UIImageView autoLayoutView];
[self.figCaptionImageView setBackgroundColor:[UIColor lightGrayColor]];
[self addSubview:figCaptionImageView];
self.figCaptionTextView = [UITextView autoLayoutView];
[self.figCaptionTextView setScrollEnabled:NO];
[self.figCaptionTextView setText:#"The digital atlas teaches the cartographic and cultural contents with a highly dynamic and visual method. The idea is based on the phenomenon of “cabinets of wonder” from the 16th and 17th century. At this time European discoverers collected during their expeditions various exotic objects and on the turn to Europe replaced the found pieces to a universal collection."];
[self addSubview:figCaptionTextView];
/**
* Then apply the constraints
*/
[self autoLayoutAddConstraints];
}
-(void)autoLayoutAddConstraints {
/**
* Any set up values that we need
*/
CGRect windowBounds = [[UIScreen mainScreen] bounds];
/**
* Dictionary of views and metrics
*/
NSDictionary *views = NSDictionaryOfVariableBindings(self, figCaptionImageView, figCaptionTextView);
NSDictionary *metrics = #{#"imageWidth": #(windowBounds.size.width), #"margin": #20.0f};
/**
* Constraints for this view (Vertical and horizontal)
*/
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[figCaptionImageView(imageWidth)]|"
options:0
metrics:metrics
views:views
]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[figCaptionImageView][figCaptionTextView]|"
options:0
metrics:metrics
views:views
]];
/**
* Constraints for the caption image view to maintain ratio
*/
[self.figCaptionImageView addConstraint:[NSLayoutConstraint constraintWithItem:self.figCaptionImageView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.figCaptionImageView
attribute:NSLayoutAttributeWidth
multiplier:0.75f
constant:0.0f
]];
/**
* Constraints for the caption text view - horizontal
*/
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[figCaptionTextView]|"
options:0
metrics:metrics
views:views
]];
}
#end
Incase you were also wondering, I have included the implementation for UIView+Autolayout
** UIView+Autolayout.m **
//
// UIView+Autolayout.m
// Anna Christoffer
//
// Created by Matthew Finucane on 19/12/2014.
// Copyright (c) 2014 Anna Christoffer. All rights reserved.
//
#import "UIView+Autolayout.h"
#implementation UIView (Autolayout)
+(id)autoLayoutView {
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
#end
You can try:
[captionImageView setClipsToBounds:YES];
try it right after you set aspect mode...
this might help: Crop UIImage to fit a frame image
EDIT
I just said about clipToBounds because even using autolayout from interface builder i had problems with my images in AspectFill mode, they would not respect the bounds of the imageview. But seems like your problem has more to do with layout constraints.
Try these constraints (notice the - sign next to the superview denoted as pipe |), it just adds the default aqua space to the constraints, it's simple but may work:
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-[captionImageView]-|" options:0 metrics:metrics views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[captionTextView]|" options:0 metrics:metrics views:views]];
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[captionImageView(imageHeight)][captionTextView]|" options:NSLayoutFormatAlignAllLeft metrics:metrics views:views]];
In iOS8 extensions, specifically the share extension, has anyone been able to override the loadPreviewView method to supply a custom preview view? I created one by returning a 50x50 UIView with a UIIMageView subview, but it shows up outside of the extension view (too far right) and it does not push the textView in the share extension over to the left. If anyone has customized this, please provide sample code! Thanks
Yep, I could get it working using width & height constraints. If I set a size and a mask it would not show up properly.
Here is a sample code:
- (UIView *)loadPreviewView {
UIView * previewView = [super loadPreviewView];
if (previewView == nil) {
previewView = [[UIImageView alloc] initWithFrame:CGRectZero];
[previewView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[previewView(90)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(previewView)]];
[previewView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[previewView(90)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(previewView)]];
}
return previewView;
}
Alternatively, you can derive from UIImageView and provide an implementation for intrinsicContentSize:
#interface MyImageView : UIImageView
#end
#implementation MyImageView
-(CGSize)intrinsicContentSize {
return CGSizeMake(70, 70);
}
#end
It's detailed in this WWDC session: https://developer.apple.com/videos/play/wwdc2015/224/?time=334
It's likely you'll also want to configure you view like so:
view.clipsToBounds = YES;
view.contentMode = UIViewContentModeScaleAspectFill;
I set the image of a UIImageView to an image that is 1024x1024, and as a result a lot of the image is not visible, especially width wise, and cut off the edges of the screen.
I tried using clipsToBounds:
UIImageView *imageFromLink = [[UIImageView alloc] initWithImage:responseObject];
imageFromLink.clipsToBounds = YES;
[darkOverlayView addSubview:imageFromLink];
But it doesn't seem to do anything, and the image is still too big for the view.
You're going to want to change the contentMode property for the desired effect. UIViewContentModeScaleAspectFill is most likely what you'll want.
You have the set the image view's frame to the size you want. By default it will be the size of the image.
UIImageView *imageFromLink = [[UIImageView alloc] initWithImage:responseObject];
imageFromLink.contentMode = UIViewContentModeScaleAspectFit;
imageFromLink.frame = CGRectMake(0, 0, desiredWidth, desiredHeight);
[darkOverlayView addSubview:imageFromLink];
Also set the contentMode so the image is scaled properly in the smaller image view.
You should set the imageview's frame equal to the container's bounds.
UIImageView *imageFromLink = [[UIImageView alloc]initWithImage:responseObject];
imageFromLink.contentMode = UIViewContentModeScaleAspectFit;
imageFromLink.frame = darkOverlayView.bounds;
[darkOverlayView addSubview:imageFromLink];