PictureBoxコントロールに任意のサイズに変更して描画する
.NET Compact Frameworkは、.NET Frameworkからモバイル向けにいくつか機能を削除されています。
PictureBoxコントロールのSizeModeプロパティにZoomが設定出来ません。その為アプリ側で縮小サイズを計算して描画する必要があります。
今回は、ファイルを読み込み画像データを任意の位置とサイズにて、PictureBoxへ描画する方法をご紹介します。
最初に、buttonとpictureBoxコントロールを適当な位置に貼り付けておいてください。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim filePath As String = "\Storage Card\miku kirintamura.jpg"
' 表示したい画像を読み込む
Dim srcImage As Image = New Bitmap(filePath)
' 入力する画像の座標とサイズを指定する
Dim srcX As Integer = 0
Dim srcY As Integer = 0
Dim srcWidth As Integer = srcImage.Width
Dim srcHeight As Integer = srcImage.Height
Dim srcRect As New Rectangle(srcX, srcY, srcWidth, srcHeight)
' 出力する画像の座標とサイズを指定する
' 値は任意のサイズ
Dim dstX As Integer = 0
Dim dstY As Integer = 0
Dim dstWidth As Integer = 114
Dim dstHeight As Integer = 175
Dim dstRect As New Rectangle(dstX, dstY, dstWidth, dstHeight)
' 画像データの長さの単位を指定する
Dim units As GraphicsUnit = GraphicsUnit.Pixel
' Graphicsオブジェクトを利用して描画を行う
Dim bmp As New Bitmap(dstWidth, dstHeight)
Using g As Graphics = Graphics.FromImage(bmp)
g.DrawImage(srcImage, dstRect, srcRect, units)
End Using
' PictureBoxへ表示
Me.PictureBox1.Image = bmp
End Sub
private void Button1_Click(System.Object sender, System.EventArgs e)
{
string filePath = "\\Storage Card\\miku kirintamura.jpg";
// 表示したい画像を読み込む
Image srcImage = new Bitmap(filePath);
// 入力する画像の座標とサイズを指定する
int srcX = 0;
int srcY = 0;
int srcWidth = srcImage.Width;
int srcHeight = srcImage.Height;
Rectangle srcRect = new Rectangle(srcX, srcY, srcWidth, srcHeight);
// 出力する画像の座標とサイズを指定する
// 値は任意のサイズ
int dstX = 0;
int dstY = 0;
int dstWidth = 114;
int dstHeight = 175;
Rectangle dstRect = new Rectangle(dstX, dstY, dstWidth, dstHeight);
// 画像データの長さの単位を指定する
GraphicsUnit units = GraphicsUnit.Pixel;
// Graphicsオブジェクトを利用して描画を行う
Bitmap bmp = new Bitmap(dstWidth, dstHeight);
using (Graphics g = Graphics.FromImage(bmp)) {
g.DrawImage(srcImage, dstRect, srcRect, units);
}
// PictureBoxへ表示
this.PictureBox1.Image = bmp;
}
上記のコードを実行すると、エミュレータでの結果のように画像が任意の大きさ・位置に描画されます。
![]()
(注意)サンプルのミクは もしかして:ぎんしゃり。 の了承を得て使用させて頂いております。