Sample Code: Create a glyph from an image

Glyphs can be defined in a number of ways. One common use case is creating a glyph from an image. The following code will demonstrate how to do that:

bool addGlyphFromImage(HPS::PortfolioKey pKey, wstring name, wstring image) { if (!name.empty() && !image.empty() && !pKey.Empty()) { Gdiplus::Bitmap icon(image.c_str()); icon.RotateFlip(Gdiplus::RotateNoneFlipY); Gdiplus::Color clr; auto w = icon.GetWidth(); auto h = icon.GetHeight(); icon.GetPixel(20, 20, &clr); HPS::GlyphKit glyph_kit; HPS::GlyphElementArray elements; HPS::DotGlyphElement pixel; if (w <= 256 && h <= 256) { for (int row = 0; row < h; row++) { for (int col = 0; col < w; col++) { icon.GetPixel(row, col, &clr); if (clr.GetA() != 0) { pixel.SetPoint(GlyphPoint((sbyte)(row + 127), (sbyte)(col - 128))); pixel.SetExplicitColor(RGBAColor(clr.GetR() / 255.0, clr.GetG() / 255.0, clr.GetB() / 255.0, clr.GetA() / 255.0)); elements.push_back(pixel); } } } glyph_kit.SetElements(elements).SetOffset(HPS::GlyphPoint(0, 0)).SetRadius(127); char * charName = (char *)malloc(name.length() + 1); size_t i; // convert wstring to char * for DefineGlyph function wcstombs_s(&i, charName, (size_t)name.length() + 1, name.c_str(), (size_t)name.length() + 1); pKey.DefineGlyph(charName, glyph_kit); if (charName) { free(charName); } return true; } } return false; }

 

Are you using C#? The following code is the C# equivalent:

 

using HPS; using System.Drawing; using System.Collections.Generic; namespace HPSUtils { class ImageTools { public ImageTools() {} public bool AddGlyphFromImage(HPS.PortfolioKey pKey, string name, string image) { if (name != string.Empty && image != string.Empty && pKey != null) { HPS.GlyphKit glyph_kit = new GlyphKit(); List<HPS.GlyphElement> elements = new List<HPS.GlyphElement>(); HPS.DotGlyphElement pixel; Bitmap icon = new Bitmap(image); icon.RotateFlip(RotateFlipType.RotateNoneFlipY); Color clr; if (icon.Height <= 256 || icon.Width <= 256) { for (int row = 0; row < icon.Height; row++) { for (int col = 0; col < icon.Width; col++) { clr = icon.GetPixel(row, col); if (clr.A != 0) { pixel = new HPS.DotGlyphElement(); pixel.SetPoint(new GlyphPoint((sbyte)(row + 127), (sbyte)(col - 128))); pixel.SetExplicitColor(new RGBAColor(clr.R / 255f, clr.G / 255f, clr.B / 255f, clr.A / 255f)); elements.Add(pixel); } } } glyph_kit.SetElements(elements.ToArray()).SetOffset(new HPS.GlyphPoint(0, 0)).SetRadius(127); pKey.DefineGlyph(name, glyph_kit); return true; } } return false; } } }

Additional Resources

More information can be found in our Programming Guide page about Defining And Using Glyphs.