Some Code

I don’t think there’s been any code published on the blog before, so i thought for a change, I’d put up what I’ve been working with this morning.

As we’re working with images, I thought it would be cool to be able to have my image and then perhaps overlay a frame of some kind on top to give the impression (for example) that the image is ‘stuck’ in a ‘photo album’. After a little bit of trial-error-giving-up-and-googling, i came across this blog post which did kind of what I wanted… http://www.realdevelopers.com/blog/?p=415

A quick look at the code and it seemed simple enough, so I thought I would convert it to C# for use in MonoTouch. After a small amount of confusion (revolving around the pointer to and allocation of ‘bitmapData’) it now works.

Here we go… a useful bit of code to composite images in MonoTouch…



using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;

namespace ImageOverlayRotate
{

	public class ImageUtils
	{

		public ImageUtils ()
		{
		}

		public UIImage overlayImage (UIImage image, UIImage overlay,
				RectangleF imageRect, RectangleF overlayRect,
				SizeF size)
		{
			RectangleF imageBoundingBox = imageRect;
			RectangleF overlayBoundingBox = overlayRect;

			CGBitmapContext context = createBitmapOfSize(size);

			context.SetRGBFillColor(1,1,1,1);
			context.FillRect(imageBoundingBox);
			//context.ClearRect(iconBoundingBox);

			context.DrawImage(imageBoundingBox, image.CGImage);
			context.DrawImage(overlayBoundingBox,overlay.CGImage);
			UIImage result = UIImage.FromImage(context.ToImage());
			return result;
		}

		private CGBitmapContext createBitmapOfSize (SizeF size)
		{
			CGColorSpace colorspace;
			int bitmapBytesPerRow;

			bitmapBytesPerRow = (int)(size.Width * 4);
			colorspace = CGColorSpace.CreateDeviceRGB ();

			CGBitmapContext context = new CGBitmapContext (
					IntPtr.Zero,
					(int)size.Width,
					(int)size.Height,
					8,
					bitmapBytesPerRow,
					colorspace,
					CGImageAlphaInfo.PremultipliedLast
				);

			context.SetAllowsAntialiasing (false);

			return context;
		}
	}

About these ads

Tags: , , , , ,

3 Responses to “Some Code”

  1. MonoTouch.Info Says:

    MonoTouch Article – Overlay / Composite Two Images…

    Thank you for submitting this entry – Trackback from MonoTouch.Info…

  2. johnny hughes Says:

    It looks like you aren’t releasing resources?

  3. IPhone Development Says:

    .Net + iPhone = Winner

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: