WindowsFormプログラムで背景を透過しながらキャラクタを移動する
アルファ値(透過)を持ったPngファイルを用意して、透過キャラを表示、移動するサンプルになります。
実行イメージ
サンプルコード
用意するもの
- 2つの透過画像(pngファイル)
- ちらつき防止のためForm1のDoubleBufferedプロパティをTrueにセットします。
- Timerは精度を上げるため、Window.Forms.Timerクラスではなく、Timersクラスを使います。
Form1.csサンプル
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
namespace BitmapTransSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int x = 0;
int y = 0;
Bitmap bitmap1;
Bitmap bitmap2;
protected override void OnPaint(PaintEventArgs e)
{
Graphics FormG = this.CreateGraphics();
bitmap2.SetResolution(FormG.DpiX, FormG.DpiY);
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
e.Graphics.DrawImage(bitmap1, x * 100, y * 100);
}
}
e.Graphics.DrawImage(bitmap2, x, 0);
e.Graphics.DrawImage(bitmap2, x * 1.2f,100);
e.Graphics.DrawImage(bitmap2, x * 1.5f, 200);
e.Graphics.DrawImage(bitmap2, 100, y * 1.2f);
e.Graphics.DrawImage(bitmap2, 150, y * 1.7f);
e.Graphics.DrawImage(bitmap2, 200, y * 2.0f);
e.Graphics.DrawImage(bitmap2, x * 1.2f, y * 1.2f);
e.Graphics.DrawImage(bitmap2, x * 1.7f, y * 1.7f);
e.Graphics.DrawImage(bitmap2, x * 1.7f, y * 2.0f);
}
private void Form1_Load(object sender, EventArgs e)
{
bitmap1 = new Bitmap(Properties.Resources.pie1);
bitmap2 = new Bitmap(Properties.Resources.pie2);
// タイマーの生成
var timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnElapsed_TimersTimer);
timer.Interval = 20;
// タイマーを開始
timer.Start();
}
private void OnElapsed_TimersTimer(object sender, ElapsedEventArgs e)
{
if (x > 300)
{
x = 0;
}
if (y > 300)
{
y = 0;
}
x += 10;
y += 10;
Invalidate();
}
}
}
DoubleBuffered = true;
Form1.Designer.csサンプル
namespace BitmapTransSample
{
partial class Form1
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージド リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(1298, 956);
this.DoubleBuffered = true;
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
ディスカッション
コメント一覧
まだ、コメントがありません