1

I have created a UIImageview programmatically, and I am showing an image from a string which contains url of a picture

But I wish to show a part(a rectangle at center) of the original image. How do I achieve this?

    NSString * urlString = @"http://4.bp.blogspot.com/-  rEqVgkdnuxE/TWd6Fm6EWtI/AAAAAAAABSc/cWCehI51v_Y/s1600/red_rose_flower3.jpg"

   NSURL *url = [NSURL URLWithString:urlstring];
   NSData *data = [NSData dataWithContentsOfURL:url];
   UIImage *img = [[UIImage alloc] initWithData:data];
Dan F
  • 17,654
  • 5
  • 72
  • 110
  • You can read more information in these answers: http://stackoverflow.com/questions/8035673/most-efficient-way-to-draw-part-of-an-image-in-ios – Dave Nov 26 '12 at 16:53

2 Answers2

1

Try this on for size :)

UIImageView *imageView = [UIImageView alloc] initWithImage:image];
[imageView setFrame:SIZEOFRECTANGLE];
[imageView setContentModeCenter];
Ryan Poolos
  • 18,421
  • 4
  • 65
  • 98
  • This code has one problem on retina screen. Let I have a picture with image size 400px x 400px and want to see its center view in the frame of size 200pt x 200pt. System interprets your image as retina image of 800px x 800px and get its half to fill area of 200pt x 200pt = 400px x 400px. Thus, you'll the center of your initial image twice magnified and effectively with twice worse quality. – malex Oct 16 '13 at 12:14
  • In the code above you must add important line *imageView.clipsToBounds = YES;* Without it you'll still see the whole image out the bounds of UIImageView – malex Oct 16 '13 at 12:24
0

The very simple way to move big image inside UIImageView as follows.

Let we have the image of size (imgX, imgY) in pixels and we want to show its center in the frame of size (sizeX, sizeY) in points. The solution is:

UIImageView *iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, sizeX, sizeY)];
iView.image = [UIImage imageNamed:@"NAME"];
CGRect contentFrame = CGRectMake(1/2-sizeX/imgX, 1/2-sizeY/imgY, 2*sizeX/imgX, 2*sizeY/imgY);
iView.layer.contentsRect = contentFrame;

Here contentFrame is normalized frame relative to real UIImage size. It will be the original view of image without magnifications.

malex
  • 9,874
  • 3
  • 56
  • 77