MyImage.vb 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. Imports System.Threading.Tasks
  2. Public Class MyImage
  3. Inherits Image
  4. '事件
  5. Private _SourceData As String = ""
  6. Private _UseCache As Boolean = False
  7. Private _DownloadTask As Task
  8. Private FileCacheExpiredTime As TimeSpan = New TimeSpan(7, 0, 0, 0) ' 一个星期的缓存有效期
  9. Public Property UseCache As Boolean
  10. Get
  11. Return _UseCache
  12. End Get
  13. Set(value As Boolean)
  14. _UseCache = value
  15. End Set
  16. End Property
  17. ''' <summary>
  18. ''' 重写Image的Source属性
  19. ''' </summary>
  20. Public Shadows Property Source As String
  21. Get
  22. Return _SourceData
  23. End Get
  24. Set(value As String)
  25. If String.IsNullOrEmpty(value) Then Exit Property
  26. _SourceData = value
  27. Try
  28. If Not value.StartsWithF("http") Then ' 本地资源直接使用
  29. MyBase.Source = New MyBitmap(_SourceData)
  30. Exit Property
  31. End If
  32. If _DownloadTask IsNot Nothing AndAlso Not _DownloadTask.IsCompleted Then ' 之前下载任务还在,直接砍了
  33. _DownloadTask.Dispose()
  34. End If
  35. Dim NeedDownload As Boolean = True '是否需要下载/本地是否有有效缓存
  36. Dim TempFilePath As String = PathTemp & "Cache\MyImage\" & GetHash(_SourceData) & ".png"
  37. If _UseCache And File.Exists(TempFilePath) And (DateTime.Now - File.GetCreationTime(TempFilePath)) < FileCacheExpiredTime Then NeedDownload = False ' 缓存文件存在且未过期,不需要重下
  38. If Not NeedDownload Then
  39. MyBase.Source = New MyBitmap(TempFilePath)
  40. Exit Property
  41. End If
  42. ' 异步下载图片
  43. Dim TaskID = 0
  44. _DownloadTask = New Task(Sub()
  45. NetDownload(_SourceData, TempFilePath, True)
  46. End Sub)
  47. TaskID = _DownloadTask.Id
  48. _DownloadTask.Start()
  49. _DownloadTask.ContinueWith(Sub(t)
  50. If t.IsCompleted AndAlso t.Id = TaskID Then ' 任务没有被干掉
  51. MyBase.Source = New MyBitmap(TempFilePath)
  52. End If
  53. End Sub, TaskScheduler.FromCurrentSynchronizationContext())
  54. Catch ex As Exception
  55. Log(ex, "加载图片失败")
  56. End Try
  57. End Set
  58. End Property
  59. Public Shared Shadows ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(String), GetType(MyImage), New PropertyMetadata(New PropertyChangedCallback(
  60. Sub(sender As DependencyObject, e As DependencyPropertyChangedEventArgs)
  61. If Not IsNothing(sender) Then
  62. If String.IsNullOrEmpty(e.NewValue.ToString()) Then Exit Sub
  63. CType(sender, MyImage).Source = e.NewValue.ToString()
  64. End If
  65. End Sub)))
  66. End Class