Merge Images

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to merge images together using an image context.

Recipe

  1. Create a new Single View Application called MergeImages.
  2. Add two images named monkey1.png and monkey2.png to the project with a Build Action of BundleResource. See the sample project that goes with this recipe for sample images.
  3. For simplicity here, we’ll just work within the AppDelegate. Add the following class variables to the AppDelegate.
UIImage image1;
UIImage image2;
UIImage combinedImage;
UIImageView combinedImageView;
  1. In the FinishedLaunching method, load the two UIImage instances from the files added earlier.
image1 = UIImage.FromFile ("monkey1.png");
image2 = UIImage.FromFile ("monkey2.png");
  1. Draw both images to an image context and retrieve the merged image by calling UIGraphics.GetImageFromCurrentContext.
image1.Draw (new CoreGraphics.CGRect (
                0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height));

image2.Draw (new CoreGraphics.CGRect (
UIScreen.MainScreen.Bounds.Width / 4,
UIScreen.MainScreen.Bounds.Height / 4,
UIScreen.MainScreen.Bounds.Width / 2,
UIScreen.MainScreen.Bounds.Height / 2));

combinedImage = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
  1. To display the image, create an ImageView and set its Image property to the merged image. Then add the ImageView as a sub view of the controller’s view.
combinedImageView = new UIImageView (
new CoreGraphics.CGRect (0, 0, UIScreen.MainScreen.Bounds.Width,
UIScreen.MainScreen.Bounds.Height));  

combinedImageView.Image = combinedImage;

viewController.View.AddSubview (combinedImageView);

Additional Information

The UIGraphics.GetImageFromCurrentImageContext method returns a UIImage for whatever has been drawn to the current graphics context.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.