.NET Compact Frameworkは、.NET Frameworkからモバイル向けにいくつか機能を削除されています。 PictureBoxコントロールのSizeModeプロパティにZoomが設定出来ません。その為アプリ側で縮小サイズを計算して描画する必要があります。
今回は、ファイルを読み込み画像データを任意の位置とサイズにて、PictureBoxへ描画する方法をご紹介します。
PictureBoxに任意のサイズの画像を表示する
まず、buttonとpictureBoxコントロールを適当な位置に貼り付けておいてください。
usingディレクティブに
- using System.Drawing.Imaging;
を追加しておきます。
C#
private void Draw(Image dstImage, string filePath) { // 表示したい画像を読み込む 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 = 70; int dstY = 20; int dstWidth = 114; int dstHeight = 175; Rectangle dstRect = new Rectangle(dstX, dstY, dstWidth, dstHeight); // その他諸々指定する GraphicsUnit units = GraphicsUnit.Pixel; // Graphicsオブジェクトを利用して描画を行う Graphics g = Graphics.FromImage(dstImage); g.DrawImage(srcImage, dstRect, srcRect, units); }
VB.NET
Private Sub Draw(ByVal dstImage As dstImage, ByVal filePath As String) ' 表示したい画像を読み込む 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
呼び元で、
LoadDraw(pictureBox1.Image, @"\My Documents\マイ ピクチャ\miku%20kirintamura.jpg");
と、任意のファイルパスを渡しますと、下記のように画像が任意の大きさ・位置に描画されます。