Search code examples
iphoneiosrenderlayerbounds

changing the bounds property of UIView in iOS, then rendering image


In my app:

  • I have a view (UIView *myView) wihth clipsToBound = YES;

  • I have a button to do changing the origin of bounds property:

CGRect newRect = myView.bounds;
newRect.origin.x += 100;
myView.bounds = newRect;
myView.layer.frame = newRect;
  • Then I get the image from the view:
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage_after = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage_after, nil, nil, nil);

It produces the image I don't expected. I want a image as I see in the iPhone's screen.

Link for the code here: http://www.mediafire.com/?ufr1q8lbd434wu1

Please help me!


Solution

  • You don't want to render the image itself in your context - that will always render in the same way (you're not altering the image, you're jsut moving how far up the view it is).

    You want to render the image's parent view like this :

    UIGraphicsBeginImageContext(myView.superview.bounds.size);
    [myView.superview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage_after = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage_after, nil, nil, nil);
    

    EDIT

    However, you might not want to render everything in your superview :)

    Your views might look something like

    MainView
       ImageView (myView)
       UIButton (ok button)
       UIButton (cancel button)
    

    Here, rendering your image's superview will render MainView - including the buttons!

    You need to add another view into your hierachy like this :

    MainView
      UIView (enpty uiview)
        ImageView (myView)
      UIButton (ok button)
      UIButton (cancel button)
    

    Now, when you render your image's superview, it's only got the image inside it - the buttons don't get rendered :)