68 lines
2.5 KiB
C#
68 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing.Imaging;
|
|
using System.Drawing;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Drawing.Text;
|
|
|
|
namespace SoraV2Utils_Agent
|
|
{
|
|
internal class DynamicIcon
|
|
{
|
|
public static Icon CreateIcon(string text, Color textColor, Font font)
|
|
{
|
|
if (string.IsNullOrEmpty(text) || text.Length > 3)
|
|
throw new ArgumentException("Text must be between 1 and 3 characters long.", nameof(text));
|
|
|
|
// Create a 32x32 transparent bitmap
|
|
using (Bitmap bitmap = new Bitmap(32, 32))
|
|
{
|
|
using (Graphics g = Graphics.FromImage(bitmap))
|
|
{
|
|
// Set up transparency
|
|
g.Clear(Color.Transparent);
|
|
|
|
// Enable anti-aliasing for smoother text
|
|
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
|
|
|
|
// Determine the largest font size that will fit within 32x32
|
|
float maxFontSize = 48; // Start with a large font size
|
|
SizeF textSize;
|
|
Font adjustedFont;
|
|
do
|
|
{
|
|
maxFontSize--;
|
|
adjustedFont = new Font(font.FontFamily, maxFontSize, font.Style);
|
|
textSize = g.MeasureString(text, adjustedFont);
|
|
}
|
|
while ((textSize.Width > 42 || textSize.Height > 42) && maxFontSize > 1);
|
|
|
|
if (textSize.Width > 42 || textSize.Height > 42)
|
|
{
|
|
// Reduce back if the scaled size exceeds 32x32
|
|
maxFontSize /= 1.25f;
|
|
adjustedFont = new Font(font.FontFamily, maxFontSize, font.Style);
|
|
textSize = g.MeasureString(text, adjustedFont);
|
|
}
|
|
|
|
// Calculate the position to center the text
|
|
float x = (32 - textSize.Width) / 2;
|
|
float y = (32 - textSize.Height) / 2;
|
|
|
|
// Draw the text
|
|
using (SolidBrush textBrush = new SolidBrush(textColor))
|
|
{
|
|
g.DrawString(text, adjustedFont, textBrush, x, y);
|
|
}
|
|
}
|
|
|
|
// Create and return the icon
|
|
return Icon.FromHandle(bitmap.GetHicon());
|
|
}
|
|
}
|
|
}
|
|
}
|