Section 17.11. Loading, Displaying and Scaling Images


17.11. Loading, Displaying and Scaling Images

Visual Basic's multimedia capabilities include graphics, images, animations and video. Previous sections demonstrated vector-graphics capabilities; this section presents image manipulation. The application in Fig. 17.23 loads an Image (System.Drawing namespace), then allows the user to scale the Image to a specified width and height.

Figure 17.23. Image resizing.

  1  ' Fig. 17.23: FrmDisplayLogo.vb  2  ' Displaying and resizing an image  3  Public Class FrmDisplayLogo  4     Private imageValue As Image  5     Private graphicsObject As Graphics 6  7     ' load image and obtain Graphics object  8     Private Sub FrmDisplayLogo_Load(ByVal sender As Object, _  9        ByVal e As System.EventArgs) Handles Me.Load 10 11        imageValue = Image.FromFile("images\Logo.gif") 12        graphicsObject = Me.CreateGraphics() 13     End Sub ' FrmDisplayLogo_Load 14 15     ' get new width and height of image, then redraw it 16     Private Sub btnSet_Click(ByVal sender As System.Object, _ 17        ByVal e As System.EventArgs) Handles btnSet.Click 18        ' get user input 19        Dim Width As Integer = Convert.ToInt32(widthTextBox.Text) 20        Dim Height As Integer = Convert.ToInt32(heightTextBox.Text) 21 22        ' if dimensions specified are too large 23        ' display problem 24        If Width > 375 Or Height > 225 Then 25           MessageBox.Show(" Height or Width too large") 26           Return 27        End If 28 29        ' clear the Form then draw the image 30        graphicsObject.Clear(Me.BackColor)                       31        graphicsObject.DrawImage(imageValue, 5, 5, Width, Height) 32     End Sub ' btnSet_Click 33  End Class ' FrmDisplayLogo 

Line 4 declares Image variable image. Line 11 in the Form's Load event handler uses Shared Image method FromFile to load an image from a file on disk. Line 12 uses the Form's CreateGraphics method to create a Graphics object for drawing on the Form. Method CreateGraphics is inherited from class Control. When you click the Set Button, lines 2427 validate the width and height to ensure that they are not too large. If the parameters are valid, line 30 calls Graphics method Clear to paint the entire Form in the current background color. Line 31 calls Graphics method DrawImage, passing as arguments the image to draw, the x-coordinate of the image's upper-left corner, the y-coordinate of the image's upper-left corner, the width of the image and the height of the image. If the width and height do not correspond to the image's original dimensions, the image is scaled to fit the new width and height.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net