Skip to content

Instantly share code, notes, and snippets.

@YDKK
Last active August 15, 2017 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YDKK/1a3199934ca1d5f6f5c8b2bc923cf915 to your computer and use it in GitHub Desktop.
Save YDKK/1a3199934ca1d5f6f5c8b2bc923cf915 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace CapyPuzzleSolver
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private class Pixel
{
public byte R { get; }
public byte G { get; }
public byte B { get; }
public int Index { get; }
public Pixel(IList<byte> data, int index)
{
B = data[0];
G = data[1];
R = data[2];
Index = index;
}
}
private static (int x1, int x2, int y1, int y2) Solve(BitmapSource source)
{
var width = source.PixelWidth;
var height = source.PixelHeight;
var stride = width * source.Format.BitsPerPixel / 8;
var data = new byte[stride * height];
source.CopyPixels(data, stride, 0);
var pixels = data.Buffer(source.Format.BitsPerPixel / 8).Select((x, i) => new Pixel(x, i));
var list = new List<(int x, int y)>();
//何故か背景色がFFA07A固定なのでそれ使って適当に
list.AddRange(pixels.Where(x =>
Math.Abs(x.R - 0xFF) < 5 &&
Math.Abs(x.G - 0xA0) < 5 &&
Math.Abs(x.B - 0x7A) < 5
).Select(x => (x.Index % width, x.Index / width)));
var x1 = list.Min(x => x.x);
var x2 = list.Max(x => x.x);
var y1 = list.Min(x => x.y);
var y2 = list.Max(x => x.y);
return (x1, x2, y1, y2);
}
private void SetRectangle((int x1, int x2, int y1, int y2) result)
{
Rectangle.Margin = new Thickness(result.x1 - 5, result.y1 - 5, 0, 0);
Rectangle.Width = result.x2 - result.x1 + 10;
Rectangle.Height = result.y2 - result.y1 + 10;
}
private void MainWindow_OnMouseDown(object sender, MouseButtonEventArgs e)
{
if (Clipboard.ContainsImage())
{
var image = Clipboard.GetImage();
var bitmap = new FormatConvertedBitmap(image, PixelFormats.Bgr32, null, 0);
Image.Source = bitmap;
SetRectangle(Solve(bitmap));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment