You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.1 KiB
66 lines
2.1 KiB
1 year ago
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
using SkiaSharp;
|
||
1 year ago
|
using StabilityMatrix.Core.Extensions;
|
||
|
|
||
1 year ago
|
namespace StabilityMatrix.Avalonia.Helpers;
|
||
1 year ago
|
|
||
|
public static class ImageProcessor
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// Get the dimensions of a grid that can hold the given amount of images.
|
||
|
/// </summary>
|
||
|
public static (int rows, int columns) GetGridDimensionsFromImageCount(int count)
|
||
|
{
|
||
|
if (count <= 1) return (1, 1);
|
||
|
if (count == 2) return (1, 2);
|
||
|
|
||
|
// Prefer one extra row over one extra column,
|
||
|
// the row count will be the floor of the square root
|
||
|
// and the column count will be floor of count / rows
|
||
|
var rows = (int) Math.Floor(Math.Sqrt(count));
|
||
|
var columns = (int) Math.Floor((double) count / rows);
|
||
|
return (rows, columns);
|
||
|
}
|
||
|
|
||
1 year ago
|
public static SKImage CreateImageGrid(
|
||
|
IReadOnlyList<SKImage> images,
|
||
|
int spacing = 0)
|
||
1 year ago
|
{
|
||
|
var (rows, columns) = GetGridDimensionsFromImageCount(images.Count);
|
||
|
|
||
|
var singleWidth = images[0].Width;
|
||
|
var singleHeight = images[0].Height;
|
||
1 year ago
|
|
||
1 year ago
|
// Make output image
|
||
1 year ago
|
using var output = new SKBitmap(
|
||
1 year ago
|
singleWidth * columns + spacing * (columns - 1),
|
||
|
singleHeight * rows + spacing * (rows - 1));
|
||
1 year ago
|
|
||
1 year ago
|
// Draw images
|
||
1 year ago
|
using var canvas = new SKCanvas(output);
|
||
|
|
||
1 year ago
|
foreach (var (row, column) in
|
||
|
Enumerable.Range(0, rows).Product(Enumerable.Range(0, columns)))
|
||
|
{
|
||
|
// Stop if we have drawn all images
|
||
|
var index = row * columns + column;
|
||
|
if (index >= images.Count) break;
|
||
1 year ago
|
|
||
1 year ago
|
// Get image
|
||
|
var image = images[index];
|
||
1 year ago
|
|
||
1 year ago
|
// Draw image
|
||
1 year ago
|
var destination = new SKRect(
|
||
|
singleWidth * column + spacing * column,
|
||
|
singleHeight * row + spacing * row,
|
||
|
singleWidth * column + spacing * column + image.Width,
|
||
|
singleHeight * row + spacing * row + image.Height);
|
||
|
canvas.DrawImage(image, destination);
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
return SKImage.FromBitmap(output);
|
||
1 year ago
|
}
|
||
|
}
|