public ImagePackTreeNode insert(String imageID, Bitmap img) { //If not a leaf and both children are full if (!IsLeaf) { ImagePackTreeNode newNode = children[0].insert(imageID, img); if (newNode != null) { return(newNode); } return(children[1].insert(imageID, img)); } else { //If there is already an image, return if (this.imageID != null) { return(null); } Rectangle imageRect = new Rectangle(rc.Left, rc.Top, img.Width, img.Height); imageRect.Width += imagePadding; imageRect.Height += imagePadding; //If the area is too small return if (rc.Width < imageRect.Width || rc.Height < imageRect.Height) { return(null); } //If were just right accept if (rc.Width == imageRect.Width && rc.Height == imageRect.Height) { this.imageID = imageID; return(this); } //Otherwise gotta split this node and create some kids this.children[0] = new ImagePackTreeNode(imagePadding); this.children[1] = new ImagePackTreeNode(imagePadding); int dw = rc.Width - imageRect.Width; int dh = rc.Height - imageRect.Height; if (dw > dh) { children[0].rc = new Rectangle(rc.Left, rc.Top, imageRect.Width, rc.Height); children[1].rc = new Rectangle(rc.Left + imageRect.Width, rc.Top, rc.Width - imageRect.Width, rc.Height); } else { children[0].rc = new Rectangle(rc.Left, rc.Top, rc.Width, imageRect.Height); children[1].rc = new Rectangle(rc.Left, rc.Top + imageRect.Height, rc.Width, rc.Height - imageRect.Height); } return(children[0].insert(imageID, img)); } }
private void updateButton_Click(object sender, EventArgs e) { if (resizeImages.Checked) { foreach (BitmapEntry entry in images) { entry.resizeImage((int)resizeWidth.Value, (int)resizeHeight.Value); } } int padding = (int)this.padding.Value; var halfPadding = padding / 2; ImagePackTreeNode imageInfo = new ImagePackTreeNode(new Size((int)widthText.Value, (int)heightText.Value), padding); Bitmap atlas = new Bitmap((int)widthText.Value, (int)heightText.Value, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(atlas)) { foreach (BitmapEntry entry in images) { ImagePackTreeNode node = imageInfo.insert(entry.ImageFile, entry.Bitmap); if (node != null) { //Center image var size = entry.Bitmap.Size; var imageLocationRect = new Rectangle( node.LocationRect.X + halfPadding, node.LocationRect.Y + halfPadding, size.Width, size.Height ); g.DrawImage(entry.Bitmap, imageLocationRect); entry.ImageLocation = imageLocationRect; entry.ImageNodeLocation = node.LocationRect; padFillColor(entry.Bitmap, g, halfPadding, node.LocationRect); } else { MessageBox.Show(this, String.Format("Ran out of room placing image {0}. Please increase image size.", entry.ImageFile), "Size Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } } } if (PictureBox.Image != null) { PictureBox.Image.Dispose(); } PictureBox.Image = atlas; PictureBox.Size = atlas.Size; }