Live Chat Icon For mobile
Live Chat Icon

How to create my own hatch styles for brushes

Platform: WinForms| Category: Brushes

GDI+ features a TextureBrush that lets you draw repeating patterns. You can specify any bitmap to be drawn repeatedly. In this example we create bitmaps using code and attach them to a TextureBrush.


		static object[] patternSpecs = new object[] 
		{
			new short[] { 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00 },  // horizontal
			new short[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc },  // vertical
			new short[] { 0x77, 0xbb, 0xdd, 0xee, 0x77, 0xbb, 0xdd, 0xee },   // \\\ Down
			new short[] { 0xee, 0xdd, 0xbb, 0x77, 0xee, 0xdd, 0xbb, 0x77 },   // /// Up
			new short[] { 0xee, 0x00, 0xee, 0xee, 0xee, 0x00, 0xee, 0xee },   // +++ 
		}

		public static Bitmap CreateBitmapFromPattern(int pattern)
		{
			Bitmap patternBitmap;
			IntPtr hBitmap = NativeMethods.CreateBitmap(8, 8, 1, 1, (short[]) patternSpecs[pattern]);
			if (hBitmap != IntPtr.Zero)
				patternBitmap = Image.FromHbitmap(hBitmap);
			NativeMethods.DeleteObject(hBitmap);
			return patternBitmap;
		}

		public static void FillRectangle(Graphics g, Rectangle r, int pattern, Color foreColor, Color backColor) 
		{
			Bitmap bm = CreateBitmapFromPattern(pattern);
			FillRectangle(g, r, bm, foreColor, backColor);
		}
		public static void FillRectangle(Graphics g, Rectangle r, Bitmap bm, Color foreColor, Color backColor) 
		{
			if (bm != null)
			{
				Size size = bm.PhysicalDimension.ToSize();
				TextureBrush br = new TextureBrush(bm, new Rectangle(new Point(0, 0), size), ia);
				br.WrapMode = WrapMode.Tile;
                
				g.FillRectangle(br, r);
				br.Dispose();
			}             
		}

	public class NativeMethods
	{
		[DllImport('gdi32', CharSet=CharSet.Auto, ExactSpelling=true)]
		extern public static IntPtr CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, 
			[MarshalAs(UnmanagedType.LPArray)] short[] lpvBits);

		[DllImport('gdi32')]
		extern public static bool DeleteObject(IntPtr hObject)  ;

	}	

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.