PKHeX/PKHeX.WinForms/Controls/SAV Editor/BitmapAnimator.cs

101 lines
3.2 KiB
C#
Raw Normal View History

2018-07-23 03:04:28 +00:00
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
using Timer = System.Timers.Timer;
namespace PKHeX.WinForms.Controls
{
public sealed class BitmapAnimator : Timer
{
public BitmapAnimator(Image extraLayer = null)
2018-07-23 03:04:28 +00:00
{
ExtraLayer = extraLayer;
Elapsed += TimerElapsed;
}
private int imgWidth;
private int imgHeight;
private byte[] GlowData;
private readonly Image ExtraLayer;
private Image[] GlowCache;
public Image OriginalBackground;
private readonly object Lock = new object();
private PictureBox pb;
2018-07-23 03:04:28 +00:00
private int GlowInterval;
private int GlowCounter;
public int GlowFps { get; set; } = 60;
public Color GlowToColor { get; set; } = Color.LightSkyBlue;
public Color GlowFromColor { get; set; } = Color.White;
public new void Start() => throw new ArgumentException();
public new void Stop()
{
if (pb == null || !Enabled)
return;
lock (Lock)
{
Enabled = false;
pb.BackgroundImage = OriginalBackground;
}
// reset logic
GlowCounter = 0;
for (int i = 0; i < GlowCache.Length; i++)
GlowCache[i] = null;
2018-07-23 03:04:28 +00:00
}
public void Start(PictureBox pbox, Image baseImage, byte[] glowData, Image original)
2018-07-23 03:04:28 +00:00
{
Enabled = false;
imgWidth = baseImage.Width;
imgHeight = baseImage.Height;
GlowData = glowData;
2018-07-23 03:04:28 +00:00
pb = pbox;
GlowCounter = 0;
2018-07-23 03:04:28 +00:00
OriginalBackground = original;
GlowCache = new Image[GlowFps];
2018-07-23 03:04:28 +00:00
GlowInterval = 1000 / GlowFps;
Interval = GlowInterval;
Enabled = true;
}
private void TimerElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
if (!Enabled)
return; // timer canceled, was waiting to proceed
GlowCounter = (GlowCounter + 1) % (GlowInterval * 2); // loop backwards
int frameIndex = GlowCounter >= GlowInterval ? (GlowInterval * 2) - GlowCounter : GlowCounter;
lock (Lock)
{
if (Enabled)
pb.BackgroundImage = GetFrame(frameIndex);
}
2018-07-23 03:04:28 +00:00
}
private Image GetFrame(int frameIndex)
2018-07-23 03:04:28 +00:00
{
var frame = GlowCache[frameIndex];
if (frame != null)
return frame;
var elapsedFraction = (double)frameIndex / GlowInterval;
var frameColor = GetFrameColor(elapsedFraction);
var frameData = (byte[])GlowData.Clone();
ImageUtil.ChangeAllColorTo(frameData, frameColor);
frame = (Image)ImageUtil.GetBitmap(frameData, imgWidth, imgHeight).Clone();
2018-07-23 03:04:28 +00:00
if (ExtraLayer != null)
frame = ImageUtil.LayerImage(frame, ExtraLayer, 0, 0);
frame = ImageUtil.LayerImage(OriginalBackground, frame, 0, 0);
2018-07-23 03:04:28 +00:00
return GlowCache[frameIndex] = frame;
}
private Color GetFrameColor(double elapsedFraction) => ImageUtil.Blend(GlowToColor, GlowFromColor, elapsedFraction);
}
}