[Silverlight][VB]使用程式碼設定物件圖片
這裡作個小小的使用心得整理...
情境一:一般UserControl / Shape物件設定背景圖,例如Rectangle
Dim rect As New Rectangle()
Dim imgbrush As New ImageBrush()
imgbrush.ImageSource = New BitmapImage(New Uri("SomePic.jpg", UriKind.Relative))
rect.Fill = imgbrush
如果你寫得很熟了,然後你的組員也熟悉你的寫法...
rect.Fill = New ImageBrush() With{.ImageSource = New BitmapImage(New Uri("SomePic.jpg",UriKind.Relative))}
兩種寫法單純只是程式寫作上問題,都是一樣的結果,寫程式重點還是要人家看得懂。所以我寫這種東西都會特別跟成員講,我懶得寫那麼多行,給我想辦法習慣我的寫法吧! 哈哈~
ps.. BitmapImage物件需要import System.Windows.Media.Imaging
(算是)情境二:設定Image物件
這也是初學時會遇到的問題,Image物件設定圖片的屬性是Image.Source,它本身就是一個ImageSource物件了,所以不用再用imagebrush..使用如下
Dim img As New Image()
img.Source = New BitmapImage(New Uri("SomePic.jpg", UriKind.Relative))
情境三:使用webClient抓取圖片(串流)
webclient OpenReadAsync..
Dim wc As New WebClient()
AddHandler wc.OpenReadCompleted, AddressOf OpenReadCompleted
wc.OpenReadAsync(New Uri("XXXPath/image.jpg", UriKind.Relative))
OpenReadCompleted..
Private Sub OpenReadCompleted(ByVal sender As Object, ByVal e As OpenReadCompletedEventArgs)
If IsNothing(e.Error) Then
Try
Dim bitmap As New System.Windows.Media.Imaging.BitmapImage
bitmap.SetSource(e.Result)
img.Source = bitmap
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message)
End Try
End If
End Sub