GTK# で実装した 画像アニメーションアプリ(複数画像、方向や速度の個別指定) の全コードを以下にまとめました。ファイルは2つ構成です:
目次
🔹 AnimatedImage.cs
using Gtk;
using Gdk;
public class AnimatedImage
{
private Pixbuf image;
private Image widget;
private Fixed container;
private int x, y;
private int dx, dy;
private int width, height;
public AnimatedImage(Fixed container, string imagePath, int startX, int startY, int dx, int dy)
{
this.container = container;
this.image = new Pixbuf(imagePath).ScaleSimple(50, 50, InterpType.Bilinear);
this.widget = new Image(image);
this.x = startX;
this.y = startY;
this.dx = dx;
this.dy = dy;
container.Put(widget, x, y);
container.ShowAll();
this.width = 500;
this.height = 300;
}
public void Move()
{
x += dx;
y += dy;
// 範囲外になったら反対に戻す
if (x > width || x < -50)
x = dx > 0 ? -50 : width;
if (y > height || y < -50)
y = dy > 0 ? -50 : height;
container.Move(widget, x, y);
}
}
🔹 AnimationWindow.cs
using Gtk;
using System.Collections.Generic;
public class AnimationWindow : Window
{
private Fixed fixedContainer;
private List<AnimatedImage> images;
public AnimationWindow() : base("Image Animation - GTK#")
{
SetDefaultSize(650, 400);
SetPosition(WindowPosition.Center);
DeleteEvent += (o, args) => Application.Quit();
fixedContainer = new Fixed();
fixedContainer.SetSizeRequest(500, 300);
fixedContainer.ModifyBg(StateType.Normal, new Gdk.Color(255, 255, 224)); // light yellow
Add(fixedContainer);
images = new List<AnimatedImage>
{
new AnimatedImage(fixedContainer, "image1.jpg", 500, 150, -5, 0),
new AnimatedImage(fixedContainer, "image2.jpg", 250, 300, 0, -5),
new AnimatedImage(fixedContainer, "image3.jpg", 250, 300, -5, -5)
};
Timeout.Add(50, new TimeoutHandler(() =>
{
foreach (var img in images)
{
img.Move();
}
return true;
}));
ShowAll();
}
public static void Main()
{
Application.Init();
new AnimationWindow();
Application.Run();
}
}
🔹 ビルドコマンド:
mcs -pkg:gtk-sharp-3.0 -out:image_animation.exe AnimatedImage.cs AnimationWindow.cs
🔹 実行:
mono image_animation.exe
📝 注意点
image1.jpgimage2.jpgimage3.jpgは実行ファイルと同じフォルダに置いてください。.pngでも.jpgでもOK。ファイル名さえ合わせれば動きます。- ウィンドウサイズは 650×400、描画エリアは 500×300 で黄色背景です。
何か機能追加したいことがあれば遠慮なく言ってくださいね!💡