Skip to content

Instantly share code, notes, and snippets.

@hachikiina
Created May 17, 2020 01:13
Show Gist options
  • Save hachikiina/06bda66a1688334cc05ef570ca75c905 to your computer and use it in GitHub Desktop.
Save hachikiina/06bda66a1688334cc05ef570ca75c905 to your computer and use it in GitHub Desktop.
system.drawing to skiasharp
public string DrawRegularPolygonSK(int vertexCount, float radius, SocketCommandContext context, [Optional] int rndNum)
{
string imagesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", "images");
if (!Directory.Exists(imagesPath))
Directory.CreateDirectory(imagesPath);
using (SKBitmap bmp = new SKBitmap(1024, 1024))
using (SKPaint outerPaint = new SKPaint())
using (SKPaint innerPaint = new SKPaint())
using (SKPaint textPaint = new SKPaint())
using (SKCanvas canvas = new SKCanvas(bmp))
{
SKPoint center = new SKPoint(bmp.Width / 2, bmp.Height / 2);
var angle = Math.PI * 2 / vertexCount;
var points = Enumerable.Range(0, vertexCount).Select(i => SKPoint.Add(center, new SKSize((float)Math.Sin(i * angle) * radius,
(float)Math.Cos(i * angle) * radius)));
var color = GetGuildUserRoleColor(context.User as SocketGuildUser).Result;
canvas.Clear();
// this is for the filling of the polygon.
innerPaint.Color = new SKColor(color.R, color.G, color.B);
innerPaint.Style = SKPaintStyle.Fill;
innerPaint.StrokeWidth = 5f;
SKPath innerPath = new SKPath();
foreach (var point in points)
{
if (point == points.First())
innerPath.MoveTo(point);
else
innerPath.LineTo(point);
}
innerPath.Close();
canvas.DrawPath(innerPath, innerPaint);
// this is for the lines of the polygon.
outerPaint.Color = SKColors.Black;
outerPaint.StrokeWidth = 10f;
outerPaint.StrokeCap = SKStrokeCap.Round;
outerPaint.Style = SKPaintStyle.Stroke;
SKPath outerPath = new SKPath();
foreach (var point in points)
{
if (point == points.First())
outerPath.MoveTo(point);
else
outerPath.LineTo(point);
}
outerPath.Close();
canvas.DrawPath(outerPath, outerPaint);
// this is for the text.
textPaint.TextSize = 240f;
textPaint.IsAntialias = true;
if (color.R * 0.299f + color.G * 0.587f + color.B * 0.114f > 150) // decides the color of text based on bg color
textPaint.Color = SKColors.Black;
else
textPaint.Color = SKColors.White;
textPaint.Style = SKPaintStyle.StrokeAndFill;
textPaint.StrokeWidth = 15f;
textPaint.TextAlign = SKTextAlign.Center;
textPaint.GetFontMetrics(out var skFontMetrics);
canvas.DrawText(rndNum.ToString(), center.X, center.Y + skFontMetrics.CapHeight / 2, textPaint); // text's height is 188 pixels at size 240f and stroke 15f
using (var stream = File.Create(Path.Combine(imagesPath, context.Message.Id.ToString() + ".png")))
{
SKData data = SKImage.FromBitmap(bmp).Encode(SKEncodedImageFormat.Png, 100);
data.SaveTo(stream);
}
return Path.Combine(imagesPath, context.Message.Id.ToString() + ".png").ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment