public static ImageSource getQRCode() { String url = getQRCodeAddres();// baseURL + @"wechat/qrcode?deviceid=" + VZ_AppHelper.getSingleton().systemInfo.computerId; String local = AppDomain.CurrentDomain.BaseDirectory + @"\Datas\qr.png"; ImageSource imageSource = null; if (File.Exists(local)) { BitmapImage bi = new BitmapImage(new Uri(local, UriKind.Absolute)); imageSource = bi; if (imageSource != null) { imageSource.Freeze(); return(imageSource); } } for (int i = 0; i < 10; i++) { imageSource = ImageExtensions.get_Bitmap(url); if (imageSource != null) { break; } } imageSource.Freeze(); return(imageSource); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // getting value var mapName = _mapNameExtractor(value); // null check if (string.IsNullOrEmpty(mapName)) { return(Binding.DoNothing); } // prepare mapName for correct searching image resource var resourceKey = $"{_resourcePath}.{_imageResourcePrefix}{mapName.Replace(" ", string.Empty)}.png"; // search and create resource ImageSource imageResource = null; try { imageResource = Resources.Service.ResourceManager.GetMapImage(resourceKey); } catch { // catch any exceptions } imageResource?.Freeze(); return(imageResource ?? Binding.DoNothing); }
public static void PreloadImages() { //ImageCacheStroage.Instance.TopUsedImages can be changed during foreach, so we need to make a copy var imageList = new Dictionary <string, int>(_imageCache.TopUsedImages); Stopwatch.Debug($"Preload {imageList.Count} images", () => { foreach (var image in imageList) { if (!imageCache.ContainsKey(image.Key)) { ImageSource img = Load(image.Key, false); if (img != null) { img.Freeze(); //to make it copy to UI thread if (!imageCache.ContainsKey(image.Key)) { KeyValuePair <string, int> copyedImg = image; imageCache.Add(copyedImg.Key, img); } } } } }); }
/// <summary> Method calls <c>StoreMat()</c> simultaneously with controled by semaphore way to reduce the load on HDD </summary> /// <returns>A bitmap when <c>Image</c> getter called</returns> private ImageSource LoadImage(/*string path*/) { if (_storedMat == null || _image == null) { Sem.WaitOne(); StoreMat(); Sem.Release(); } //BitmapImage reducedImage = new BitmapImage(); //reducedImage.BeginInit(); ImageSource reducedImage = OpenCvSharp.Extensions.BitmapSourceConverter.ToBitmapSource(StoredMat); //MemoryStream dfg = StoredMat.ToMemoryStream(".jpg", // new ImageEncodingParam(ImwriteFlags.JpegQuality, 95), // new ImageEncodingParam(ImwriteFlags.JpegProgressive, 1), // new ImageEncodingParam(ImwriteFlags.JpegOptimize, 1)); //reducedImage.StreamSource = dfg; //reducedImage.StreamSource = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); //reducedImage.DecodePixelHeight = MainViewModel.Inst.ThumbnailSize; //reducedImage.CacheOption = BitmapCacheOption.None; //reducedImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; //reducedImage.Rotation = Rotation.Rotate0; //reducedImage.EndInit(); reducedImage.Freeze(); _image = reducedImage; return(_image); }
static System.Windows.Media.ImageSource GetImageSourceFromIcon(IntPtr hIcon) { try { if (hIcon == IntPtr.Zero) { return(null); } ImageSource img = Imaging.CreateBitmapSourceFromHIcon( hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); img.Freeze(); return(img); } catch (ArgumentException exp) { LogHelper.Debug("GetImageSourceFromIcon Failed", exp); } catch (Exception ex) { LogHelper.Debug("GetImageSourceFromIcon Failed", ex); } return(null); }
public static ImageSource SwapColors(ImageSource imageSource, ColorCallback colorCallback) { if (colorCallback == null) { throw new ArgumentNullException("colorCallback"); } ImageSource imageSource1 = imageSource; if (imageSource != null) { DrawingImage drawingImage; if ((drawingImage = imageSource as DrawingImage) != null) { ColorSwapper.SwapColorsWithoutCloning(((DrawingImage)(imageSource1 = (ImageSource)drawingImage.Clone())).Drawing, colorCallback); imageSource1.Freeze(); } else { BitmapSource bitmapSource; if ((bitmapSource = imageSource as BitmapSource) != null) { imageSource1 = (ImageSource)ColorSwapper.SwapColors(bitmapSource, colorCallback); } else { throw new ArgumentException(string.Format((IFormatProvider)CultureInfo.CurrentCulture, ExceptionStringTable.UnexpectedImageSourceType, new object[1] { (object)imageSource.GetType().Name })); } } } return(imageSource1); }
/// <summary> /// Runs field rendering thread. /// <para></para> /// Запускает поток отрисовки поля. /// </summary> public void StartRenderField() { if (fieldRenderThread != null) { return; } fieldRenderThread = new Thread(() => { Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; int renderNum = 1; while (fieldRenderThread == Thread.CurrentThread) { //if (renderManagerCheckAtField.HaveChanges) //{ ImageSource img = renderManagerCheckAtField.Render(renderNum++ % 20 == 0); img.Freeze(); try { imageField.Dispatcher.Invoke(() => { imageField.Source = img; }); } catch { fieldRenderThread = null; } //} Thread.Sleep(200); } }); fieldRenderThread.Start(); }
public static ImageSource GetIcon(string path, SHIL size) { IntPtr result = IntPtr.Zero; SHFILEINFO shFileInfo = new SHFILEINFO(); if (path.StartsWith(".") || path.StartsWith(@"\\")) { result = SHGetFileInfo(path, FileAttributes.Normal, ref shFileInfo, Marshal.SizeOf(shFileInfo), SHGFI.SHGFI_SYSICONINDEX | SHGFI.SHGFI_USEFILEATTRIBUTES); } else { PIDL pidl = ILCreateFromPath(path); result = SHGetFileInfo(pidl, FileAttributes.Normal, ref shFileInfo, Marshal.SizeOf(shFileInfo), SHGFI.SHGFI_SYSICONINDEX | SHGFI.SHGFI_PIDL); } if (result == IntPtr.Zero) { return(null); } SHGetImageList(size, ImageListId, out IImageList iImageList); SafeHICON hIcon = iImageList.GetIcon(shFileInfo.iIcon, IMAGELISTDRAWFLAGS.ILD_IMAGE); ImageSource imageSource = hIcon.ToBitmapSource(); imageSource.Freeze(); DestroyIcon(hIcon); return(imageSource); }
private ImageSource ReadFromDisk(IFileSystemObject fileSystemObject) { ImageSource bitmap = null; //lock (locker) { #if DISPLAY_DEBUG System.Diagnostics.Debug.WriteLine("Cache read from disk " + fileSystemObject.Name); #endif if (fileSystemObject is IDirectoryObject) { bitmap = _Converter.GetImage(fileSystemObject.FullName); } else if (ImageDirectory.IsImage(fileSystemObject as IFileObject)) { using (var stream = (fileSystemObject as IFileObject).OpenRead()) { bitmap = GetBitmap(stream); } } else { bitmap = _Converter.GetImage(fileSystemObject.FullName); } bitmap.Freeze(); } return(bitmap); }
static ShadowWindow() { ActiveBottomImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveBottom.png")); ActiveBottomImage.Freeze(); ActiveBottomLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveBottomLeft.png")); ActiveBottomLeftImage.Freeze(); ActiveBottomRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveBottomRight.png")); ActiveBottomRightImage.Freeze(); ActiveLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveLeft.png")); ActiveLeftImage.Freeze(); ActiveRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveRight.png")); ActiveRightImage.Freeze(); ActiveTopImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveTop.png")); ActiveTopImage.Freeze(); ActiveTopLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveTopLeft.png")); ActiveTopLeftImage.Freeze(); ActiveTopRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/ActiveTopRight.png")); ActiveTopRightImage.Freeze(); InactiveBottomImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveBottom.png")); InactiveBottomImage.Freeze(); InactiveBottomLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveBottomLeft.png")); InactiveBottomLeftImage.Freeze(); InactiveBottomRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveBottomRight.png")); InactiveBottomRightImage.Freeze(); InactiveLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveLeft.png")); InactiveLeftImage.Freeze(); InactiveRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveRight.png")); InactiveRightImage.Freeze(); InactiveTopImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveTop.png")); InactiveTopImage.Freeze(); InactiveTopLeftImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveTopLeft.png")); InactiveTopLeftImage.Freeze(); InactiveTopRightImage = new BitmapImage(new Uri("pack://application:,,,/Kfstorm.WpfExtensions;component/Images/Shadow/InactiveTopRight.png")); InactiveTopRightImage.Freeze(); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; ImageSource imageSource = null; for (int i = -1; i <= 2; i++) { if (worker.CancellationPending == true) { e.Cancel = true; break; } else { int p = _index + i; // load images if (!_imageCache.TryGetValue(p, out imageSource)) { if (p >= 0 && p < _files.Length) { // Thread.Sleep(10000); imageSource = BitmapFromUri(new Uri(_files[p])); imageSource.Freeze(); _imageCache[p] = imageSource; } } if (p == _index || p == _index + 1) { worker.ReportProgress(p); } } } if (e.Cancel) { return; } // load background image source if (_imageCache.TryGetValue(_index - 1, out imageSource)) { PreviousImageSource = imageSource; Debug.WriteLine("-1) Load " + (_index - 1) + " completed"); } if (_imageCache.TryGetValue(_index + 2, out imageSource)) { NextImageSource = imageSource; Debug.WriteLine(" 2) Load " + (_index + 2) + " completed"); } // clear old images foreach (var item in _imageCache.Where(kvp => kvp.Key <_index - 1 || kvp.Key> _index + 2).ToList()) { Debug.WriteLine("Remove " + item.Key); _imageCache.Remove(item.Key); } }
/// <summary> /// Swap the colors in an image based on a color mapping provided by the ColorCallback</summary> /// <param name="imageSource">Original image</param> /// <param name="colorCallback">Callback to provide the color mapping</param> /// <returns>Color-swapped image</returns> public static ImageSource SwapColors(ImageSource imageSource, ColorCallback colorCallback) { if (colorCallback == null) { throw new ArgumentNullException("colorCallback"); } ImageSource source = imageSource; if (imageSource == null) { return(source); } DrawingImage image = imageSource as DrawingImage; if (image != null) { source = image = image.Clone(); SwapColorsWithoutCloning(image.Drawing, colorCallback); source.Freeze(); return(source); } BitmapSource bitmapSource = imageSource as BitmapSource; if (bitmapSource == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "UnexpectedImageSourceType", new object[] { imageSource.GetType().Name })); } return(SwapColors(bitmapSource, colorCallback)); }
public static Dictionary <string, ImageSource> RefreshFromMods(ImageType source) { Dictionary <string, ImageSource> list = new Dictionary <string, ImageSource>(); string rightFolder; switch (source) { case ImageType.Goal: rightFolder = GFX_GOAL_FOLDER; break; case ImageType.Event: rightFolder = GFX_EVENT_FOLDER; break; default: throw new ArgumentOutOfRangeException(nameof(source), source, null); } //For each file in add mod folders ProjectModel model = new ViewModelLocator().Main.Project; if (model?.ListModFolders == null) { return(list); } { foreach (string modpath in model.ListModFolders) { string fullpath = modpath + rightFolder; if (!Directory.Exists(fullpath)) { continue; } foreach (string filename in Directory.GetFiles(fullpath, "*" + GFX_EXTENTION, SearchOption.TopDirectoryOnly)) { if (IMAGE_DO_NOT_LOAD.Any(filename.Contains)) { continue; } try { string imageName = Path.GetFileNameWithoutExtension(filename); //try to replace potential broken links because of typos in the file names. imageName = Array.IndexOf(ARRAY_ASSOCIATED_TYPO, imageName) != -1 ? ARRAY_FILE_NAME[Array.IndexOf(ARRAY_ASSOCIATED_TYPO, imageName)] : imageName; ImageSource result = ImageSourceForBitmap(DDS.LoadImage(filename)); result.Freeze(); list[imageName] = result; } catch (Exception) { // ignored, we don't want to kill the whole process for one missing image } } } } return(list); }
public void Load() { try { _asyncSource = new BitmapImage(new Uri(filename)); _asyncSource.Freeze(); Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action) delegate { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("AsyncSource")); } if (loaded != null) { loaded(); } }); } catch (Exception ex) { Logger.Error("An error has occured while trying to create an AsyncThumbnailImage. Filename = {0} Exception = {1}", LogSource.BackgroundTask, filename, ex); } }
public static void getNetImage(Image img, String url, int times) { if (String.IsNullOrEmpty(url) || times > 3) { return; } new Thread(new ThreadStart(() => { ImageSource imageSource = ImageExtensions.get_Bitmap(url); if (imageSource == null) { Thread.Sleep(1000); times++; getNetImage(img, url, times); return; } imageSource.Freeze(); img.Dispatcher.BeginInvoke((Action)(() => { img.Source = imageSource; img.Stretch = Stretch.Uniform; imageSource = null; })); })).Start(); }
private FileItem GetFileItem(string filePath, bool isChecked, string name) { FileInfo fInfo; try { fInfo = new FileInfo(filePath); } catch (ArgumentException) { return(null); } if (fInfo.Exists) { ImageSource imageSource = null; try { Icon fileIcon = Icon.ExtractAssociatedIcon(filePath); imageSource = Imaging.CreateBitmapSourceFromHIcon(fileIcon.Handle, new Int32Rect(0, 0, fileIcon.Width, fileIcon.Height), BitmapSizeOptions.FromEmptyOptions()); imageSource.Freeze(); } catch (ArgumentException) { imageSource = null; } return(new FileItem(filePath, imageSource, isChecked, name)); } return(null); }
public ObservableCollection <FileItem> GetAllFiles() { ObservableCollection <FileItem> fileItems = null; DirectoryInfo directory = new DirectoryInfo(this._folderPath); if (!directory.Exists) { return(null); } fileItems = new ObservableCollection <FileItem>(); foreach (FileInfo fileInfo in directory.GetFiles()) { if (_ignoreExtensionList != null && _ignoreExtensionList.Contains(fileInfo.Extension)) { continue; } Icon fileIcon = Icon.ExtractAssociatedIcon(fileInfo.FullName); ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(fileIcon.Handle, new Int32Rect(0, 0, fileIcon.Width, fileIcon.Height), BitmapSizeOptions.FromEmptyOptions()); imageSource.Freeze(); fileItems.Add(new FileItem(fileInfo.FullName, imageSource)); } return(fileItems); }
public static void PreloadImages() { //ImageCacheStroage.Instance.TopUsedImages can be changed during foreach, so we need to make a copy var imageList = new Dictionary <string, int>(ImageCacheStroage.Instance.TopUsedImages); using (new Timeit(string.Format("Preload {0} images", imageList.Count))) { foreach (var image in imageList) { if (!imageCache.ContainsKey(image.Key)) { ImageSource img = Load(image.Key, false); if (img != null) { img.Freeze(); //to make it copy to UI thread if (!imageCache.ContainsKey(image.Key)) { KeyValuePair <string, int> copyedImg = image; App.Window.Dispatcher.Invoke(new Action(() => imageCache.Add(copyedImg.Key, img))); } } } } } }
/// <summary> /// Gets image source from icon intptr /// </summary> internal static System.Windows.Media.ImageSource GetImageSourceFromIcon(IntPtr hIcon) { try { if (hIcon == IntPtr.Zero) { return(null); } ImageSource img = Imaging.CreateBitmapSourceFromHIcon( hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); img.Freeze(); return(img); } catch (ArgumentException exp) { Debug.Assert(false, exp.Message); } catch (Exception exp) { Debug.Assert(false, exp.Message); } return(null); }
/// <summary> /// Generates a thumbnail image of this given source image and sets the <see cref="Thumbnail" /> /// property. /// </summary> /// <param name="source"> /// The source image where the thumbnail should be generated of. /// </param> /// <remarks> /// <note type="implementnotes"> /// This method is also called by another thread, watch for thread safety here. /// </note> /// </remarks> /// <returns> /// A freezed <see cref="ImageSource" /> object, containg the thumbnail image. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <c>null</c>. /// </exception> protected virtual ImageSource GetThumbnailInternal(Image source) { if (source == null) { throw new ArgumentNullException(); } ImageSource thumbnail; // Using WPF classes instead of GDI+ to create the thumbnail would be better because it wouldn't // require additional conversion to an ImageSource. However when using the TransformedBitmap WPF class // to resize the image it gets attached with an Dispatcher and is that way locked to the Background- // Worker thread which maybe calls this method, its also slower than the GDI+ GetThumbnailImage method. using (MemoryStream imageStream = new MemoryStream()) { source.GetThumbnailImage( WallpaperVM.ThumbnailWidth, WallpaperVM.ThumbnailHeight, null, new IntPtr() ).Save(imageStream, ImageFormat.Bmp); thumbnail = BitmapDecoder.Create(imageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0]; } if (thumbnail.CanFreeze) { thumbnail.Freeze(); } return(thumbnail); }
public static ImageSource GetIconForImageMoniker(ImageMoniker imageMoniker) { IVsImageService2 imageService = VsAppShell.Current.GlobalServices.GetService <IVsImageService2>(typeof(SVsImageService)); ImageSource glyph = null; ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags; imageAttributes.ImageType = (uint)_UIImageType.IT_Bitmap; imageAttributes.Format = (uint)_UIDataFormat.DF_WPF; imageAttributes.LogicalHeight = 16; // IconHeight, imageAttributes.LogicalWidth = 16; // IconWidth, imageAttributes.StructSize = Marshal.SizeOf(typeof(ImageAttributes)); IVsUIObject result = imageService.GetImage(imageMoniker, imageAttributes); Object data = null; if (result.get_Data(out data) == VSConstants.S_OK) { glyph = data as ImageSource; if (glyph != null) { glyph.Freeze(); } } return(glyph); }
private void SteamId(string steamIdString) { ulong steamid; try { steamid = ulong.Parse(steamIdString); } catch (FormatException e) { MessageBox.Show(e.Message); return; } task = SteamServiceExt.GetPlayerSummaryAsync(steamid); task.ContinueWith((result) => { Player user = result.Result.Players[0]; Username = user.PersonaName; SteamID = user.SteamId; ImageSource image = SteamServiceExt.GetAvatar(user); image.Freeze(); Avatar = image; steamlist.Username = Username; steamlist.SteamID = SteamID; steamlist.GameList = new List <Game>(); steamlist.IgnoreList = new List <Game>(); OwnerViewModel.GameList = new ObservableCollection <Game>(steamlist.GameList); OwnerViewModel.IgnoreList = new ObservableCollection <Game>(steamlist.IgnoreList); FileService.SaveFile(steamlist); }); }
public virtual ImageSource LoadImage(int x, int y, int zoomLevel) { ImageSource image = null; var uri = GetUri(x, y, zoomLevel); if (uri != null) { if (IsAsync) { var buffer = new WebClient().DownloadData(uri); if (buffer != null) { using (var stream = new MemoryStream(buffer)) { image = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); image.Freeze(); } } } else { image = BitmapFrame.Create(uri); } } return(image); }
/// <summary> /// Converts a Bitmap object to WPF 'ImageSource' object and /// garbage collects to Bitmap object. /// </summary> public static ImageSource ToImageSource(this Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); try { ImageSource source = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions() ); source.Freeze(); return(source); } finally { if (!Win32Image.DeleteObject(hBitmap)) { Debug.WriteLine("BitmapEx.ToImageSource() - Unable to Delete hBitmap"); } bitmap.Dispose(); bitmap = null; GC.Collect(); } }
static IconUrlToImageCacheConverterTests() { DefaultPackageIcon = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgr24, null, new byte[3] { 0, 0, 0 }, 3); DefaultPackageIcon.Freeze(); }
private static void ReceiveIcons() { while (CanRun) { if (CanFetchIcons) { foreach (FileViewModel file in FetcherPool) { if (CanFetchIcons) { if (IconHelper.IsImageFile(file.FilePath)) { if (CanFetchIcons) { ImageSource source = IconHelper.LoadBitmapImage(file.FilePath); source.Freeze(); Application.Current?.Dispatcher?.Invoke(() => { file.Icon = source.Clone(); }); } else { break; } } else { Icon icon = IconHelper.GetIconOfFile(file.FilePath, false, false); if (CanFetchIcons) { ImageSource source = IconHelper.ToImageSource(icon); source.Freeze(); Application.Current?.Dispatcher?.Invoke(() => { file.Icon = source.Clone(); }); } else { break; } } Thread.Sleep(1); } else { break; } } FetcherPool.Clear(); StopFetching(); } } Thread.Sleep(1); }
static LuaModuleCompletionItem() { Bitmap bmp = new Bitmap(typeof(LuaCompletionItem).Assembly.GetManifestResourceStream("EspBrowser.Resources.Field.png")); IntPtr hBitmap = bmp.GetHbitmap(); image = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image.Freeze(); }
private static ImageSource GetImageSource(StockIconIdentifier identifier, StockIconOptions flags) { ImageSource imageSource = MakeImage(identifier, StockIconOptions.Handle | flags); imageSource.Freeze(); return(imageSource); }
/// <summary> /// Returns a frozen ImageSource from the icon handle. /// </summary> /// <param name="hIcon">The icon handle to convert.</param> /// <returns>A frozen ImageSource.</returns> private static ImageSource ToImageSource(IntPtr hIcon) { ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); imageSource.Freeze(); return(imageSource); }
private void UpdateMonsterInfo(Monster Monster) { // Used when starting HunterPie for the first time, since the events won't be triggered this.Visibility = Visibility.Visible; this.MonsterName.Text = Monster.Name; // Update monster health MonsterHealthBar.MaxSize = this.Width * 0.7833333333333333; MonsterHealthBar.UpdateBar(Monster.CurrentHP, Monster.TotalHP); SetMonsterHealthBarText(Monster.CurrentHP, Monster.TotalHP); // Gets monster icon MonsterIcon.Source = GetMonsterIcon(Monster.ID); SwitchSizeBasedOnTarget(); // Parts this.MonsterPartsContainer.Children.Clear(); foreach (Part mPart in Monster.Parts) { Monster_Widget.Parts.MonsterPart PartDisplay = new Monster_Widget.Parts.MonsterPart() { Style = FindResource("OVERLAY_MONSTER_PART_BAR_STYLE") as Style }; PartDisplay.SetContext(mPart, this.MonsterPartsContainer.ItemWidth); this.MonsterPartsContainer.Children.Add(PartDisplay); } // Enrage if (Monster.IsEnraged) { ANIM_ENRAGEDICON.Begin(this.MonsterHealthBar, true); ANIM_ENRAGEDICON.Begin(this.HealthBossIcon, true); EnrageTimerText.Visibility = Visibility.Visible; EnrageTimerText.Text = $"{Monster.EnrageTimerStatic - Monster.EnrageTimer:0}s"; } // Set monster crown this.MonsterCrown.Source = Monster.Crown == null ? null : (ImageSource)FindResource(Monster.Crown); this.MonsterCrown.Visibility = Monster.Crown == null ? Visibility.Collapsed : Visibility.Visible; Weaknesses.Children.Clear(); // Removes every weakness icon if (Monster.Weaknesses == null) { return; } foreach (string Weakness in Monster.Weaknesses.Keys) { ImageSource img = this.Resources[Weakness] as ImageSource; img.Freeze(); WeaknessDisplay MonsterWeaknessDisplay = new WeaknessDisplay { Icon = img, Width = 20, Height = 20 }; Weaknesses.Children.Add(MonsterWeaknessDisplay); } }
private Manager() { #region Creates Loading Threads _loaderThreadForThumbnails = new Thread(new ThreadStart(LoaderThreadThumbnails)); _loaderThreadForThumbnails.IsBackground = true; // otherwise, the app won't quit with the UI... _loaderThreadForThumbnails.Priority = ThreadPriority.BelowNormal; _loaderThreadForThumbnails.Start(); _loaderThreadForNormalSize = new Thread(new ThreadStart(LoaderThreadNormalSize)); _loaderThreadForNormalSize.IsBackground = true; // otherwise, the app won't quit with the UI... _loaderThreadForNormalSize.Priority = ThreadPriority.BelowNormal; _loaderThreadForNormalSize.Start(); #endregion #region Loading Images from Resources ResourceDictionary resourceDictionary = new ResourceDictionary(); resourceDictionary.Source = new Uri("WordsLive;component/Utils/ImageLoader/Resources.xaml", UriKind.Relative); _loadingImage = resourceDictionary["ImageLoading"] as DrawingImage; _loadingImage.Freeze(); _errorThumbnail = resourceDictionary["ImageError"] as DrawingImage; _errorThumbnail.Freeze(); #endregion # region Create Loading Animation ScaleTransform scaleTransform = new ScaleTransform(0.5, 0.5); SkewTransform skewTransform = new SkewTransform(0, 0); RotateTransform rotateTransform = new RotateTransform(0); TranslateTransform translateTransform = new TranslateTransform(0, 0); TransformGroup group = new TransformGroup(); group.Children.Add(scaleTransform); group.Children.Add(skewTransform); group.Children.Add(rotateTransform); group.Children.Add(translateTransform); DoubleAnimation doubleAnimation = new DoubleAnimation(0, 359, new TimeSpan(0, 0, 0, 1)); doubleAnimation.RepeatBehavior = RepeatBehavior.Forever; rotateTransform.BeginAnimation(RotateTransform.AngleProperty, doubleAnimation); _loadingAnimationTransform = group; #endregion }
static ShadowWindow() { //加载阴影图片 ActiveTopLeftImage = new BitmapImage(GetImageUri("ACTIVESHADOWTOPLEFT.png")); ActiveTopImage = new BitmapImage(GetImageUri("ACTIVESHADOWTOP.png")); ActiveTopRightImage = new BitmapImage(GetImageUri("ACTIVESHADOWTOPRIGHT.png")); ActiveLeftImage = new BitmapImage(GetImageUri("ACTIVESHADOWLEFT.png")); ActiveRightImage = new BitmapImage(GetImageUri("ACTIVESHADOWRIGHT.png")); ActiveBottomLeftImage = new BitmapImage(GetImageUri("ACTIVESHADOWBOTTOMLEFT.png")); ActiveBottomImage = new BitmapImage(GetImageUri("ACTIVESHADOWBOTTOM.png")); ActiveBottomRightImage = new BitmapImage(GetImageUri("ACTIVESHADOWBOTTOMRIGHT.png")); InactiveTopLeftImage = new BitmapImage(GetImageUri("INACTIVESHADOWTOPLEFT.png")); InactiveTopImage = new BitmapImage(GetImageUri("INACTIVESHADOWTOP.png")); InactiveTopRightImage = new BitmapImage(GetImageUri("INACTIVESHADOWTOPRIGHT.png")); InactiveLeftImage = new BitmapImage(GetImageUri("INACTIVESHADOWLEFT.png")); InactiveRightImage = new BitmapImage(GetImageUri("INACTIVESHADOWRIGHT.png")); InactiveBottomLeftImage = new BitmapImage(GetImageUri("INACTIVESHADOWBOTTOMLEFT.png")); InactiveBottomImage = new BitmapImage(GetImageUri("INACTIVESHADOWBOTTOM.png")); InactiveBottomRightImage = new BitmapImage(GetImageUri("INACTIVESHADOWBOTTOMRIGHT.png")); //冻结阴影图像,以便图像重复使用 ActiveTopLeftImage.Freeze(); ActiveTopImage.Freeze(); ActiveTopRightImage.Freeze(); ActiveLeftImage.Freeze(); ActiveRightImage.Freeze(); ActiveBottomLeftImage.Freeze(); ActiveBottomImage.Freeze(); ActiveBottomRightImage.Freeze(); InactiveTopLeftImage.Freeze(); InactiveTopImage.Freeze(); InactiveTopRightImage.Freeze(); InactiveLeftImage.Freeze(); InactiveRightImage.Freeze(); InactiveBottomLeftImage.Freeze(); InactiveBottomImage.Freeze(); InactiveBottomRightImage.Freeze(); }
void SetBackgroundColor(ImageSource img) { if (img != null) { img.Freeze(); ThreadPool.QueueUserWorkItem(new WaitCallback(SetBackgroundColor_Worker), img); } }
private void initialize(int sensorIdx) { Enabled = true; cameraService = SpringUtil.getService<ICameraService>(); sensorService = SpringUtil.getService<ISensorService>(); skeletonService = SpringUtil.getService<ISkeletonService>(); gestureService = SpringUtil.getService<IGestureService>(); sensorService.startSensor(sensorIdx); cameraService.startCameraService(sensorService.getSensor(sensorIdx)); skeletonService.enableSkeleton(sensorService.getSensor(sensorIdx)); gestureService.enableGestureService(sensorService.getSensor(sensorIdx)); imgHandLeft = new BitmapImage(new Uri(Application.Current.StartupUri, IMAGE_HAND_LEFT)); imgHandRight = new BitmapImage(new Uri(Application.Current.StartupUri, IMAGE_HAND_RIGHT)); imgHandLeftActive = new BitmapImage(new Uri(Application.Current.StartupUri, IMAGE_HAND_LEFT_ACTIVE)); imgHandRightActive = new BitmapImage(new Uri(Application.Current.StartupUri, IMAGE_HAND_RIGHT_ACTIVE)); imgHandLeft.Freeze(); imgHandRight.Freeze(); imgHandLeftActive.Freeze(); imgHandRightActive.Freeze(); }
/// <summary> /// Setta il colore usato dall'evidenziatore. /// </summary> private static void SetColor() { // Create the pen and brush to color the box behind the a's Brush myBrush = null; if (AlmaStyleFixPackage.Page == null) { myBrush = new SolidColorBrush(Color.FromArgb(0x20, 0x00, 0x00, 0xff)); } else { myBrush = new SolidColorBrush(Color.FromArgb( Convert.ToByte(AlmaStyleFixPackage.Page.A), Convert.ToByte(AlmaStyleFixPackage.Page.R), Convert.ToByte(AlmaStyleFixPackage.Page.G), Convert.ToByte(AlmaStyleFixPackage.Page.B))); } // myBrush.Freeze(); Brush penBrush = new SolidColorBrush(Colors.Red); penBrush.Freeze(); Pen myPen = new Pen(penBrush, 0.5); myPen.Freeze(); // draw a square with the created brush and pen System.Windows.Rect r = new System.Windows.Rect(0, 0, 5, 5); Geometry g = new RectangleGeometry(r); GeometryDrawing drawing = new GeometryDrawing(myBrush, myPen, g); drawing.Freeze(); image = new DrawingImage(drawing); image.Freeze(); }
void SetBackgroundColor(ImageSource img) { if (img != null) { img.Freeze(); if (backgroundcolor_THREAD != null) backgroundcolor_THREAD.Abort(); backgroundcolor_THREAD = new Thread(new ParameterizedThreadStart(SetBackgroundColor_Worker)); backgroundcolor_THREAD.Start(img); } }