I have an UIImageView
(red squares) that will display a UIImage
that must be scaled (I can receive images greater or smaller that the UIImageView
). After scaling it, the showed part of the UIImage
is the center of it.
What I need is to show the part of the image in the blue squares, how can I archive it?
I'm only able to get the image size (height and width), but it display the original size, when it's supposed to be the scaled one.
self.viewIm = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 120, 80)];
self.viewIm.backgroundColor = [UIColor greenColor];
self.viewIm.layer.borderColor = [UIColor redColor].CGColor;
self.viewIm.layer.borderWidth = 5.0;
UIImage *im = [UIImage imageNamed:@"benjen"];
self.viewIm.image = im;
self.viewIm.contentMode = UIViewContentModeScaleAspectFill;
// self.viewim.clipsToBounds = YES;
[self.view addSubview:self.viewIm];
I found a very good approximation on this answer. In that, the category resize the image, and use the center point to crop after that. I adapt it to crop using (0,0) as origin point. As I don't really need a category, I use it as a single method.
And my call is something like this:
To do what you're trying to do, I'd recommend looking into
CALayer
'scontentsRect
property.Since seeing your answer, I've been trying to work out the proper solution for a while, but the mathematics escapes me because
contentsRect:
's x and y parameters seem sort of mysterious... But here's some code that may point you in the right direction...Try something like this:
I've spent some time on this and finally created a Swift 3.2 solution (based on one of my answers on another thread, as well as one of the answers above). This code only allows for Y translation of the image, but with some tweaks anyone should be able to add horizontal translation as well ;)
Now you can adjust how far down or up you need the image to be by changing the
yOffset
.