public void Set_Icon_Small__Next(ContentControl control) { if (tool.Orientation != Orientation.Horizontal) { Output.Write("Can only cycle through icons when Tool is in a Horizontal orientation."); return; } currentSmallIcon = tool.Icon == null ? IconImage.SilkAccept : currentSmallIcon.NextValue<IconImage>(); tool.Icon = currentSmallIcon.ToImage(); }
/// <summary>Retrieves the path to the specified icon.</summary> /// <param name="helper">The HTML helper to extend.</param> /// <param name="icon">The icon.</param> /// <param name="greyscale">Flag indicating if the greyscale version should be retrieved.</param> public static string IconUrl(this HtmlHelper helper, IconImage icon, bool greyscale = false) { // Retrieve the folder. var iconName = icon.ToString(); string subPath = null; if (iconName.StartsWith("Silk")) { string greyscalePath = greyscale ? "/Greyscale" : null; subPath = string.Format("Silk{0}/{1}.png", greyscalePath, iconName); } if (subPath == null) throw new NotFoundException(string.Format("Cannot resolve URL to the icon '{0}'.", iconName)); // Create the complete URL. return string.Format("/{0}/Icons/{1}", Assets.AreaRegistration.Name, subPath); }
public unsafe override void Read(Stream stream, int resourceSize) { // Buffer a PNG image byte[] buffer = new byte[resourceSize]; stream.Read(buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(buffer); Bitmap pngBitmap = new Bitmap(ms); // Set XOR and AND Image IconImage iconImage = new IconImage(); iconImage.Set(pngBitmap, null, Color.Transparent); pngBitmap.Dispose(); //Transfer the data from the BMPEncoder to the PNGEncoder CopyFrom(iconImage.Encoder); }
/// <summary>Adds a button tool to the toolbar.</summary> /// <param name="toolbar">The toolbar to add to.</param> /// <param name="id">The unique identifier of the tool.</param> /// <param name="icon">The icon.</param> /// <param name="text">The text label.</param> /// <param name="orientation">The orientation of the label relative to the icon.</param> /// <param name="showDefaultBackground">Flag indicating whether the default background is rendered when the mouse is not over the tool.</param> /// <param name="toolTip">The tooltip</param> /// <param name="minWidth">The minimum width of the tool.</param> /// <param name="column">The index of the column the tool is in (0-based, zero by default).</param> /// <param name="row">The index of the row the tool is in (0-based, zero by default).</param> /// <param name="columnSpan">The number of rows the tool spans (1-based, one by default. Must be 1 or greater).</param> /// <param name="rowSpan">The number of columns the tool spans (1-based, one by default. Must be 1 or greater).</param> public static IButtonTool AddButton( this IToolBar toolbar, object id = null, IconImage icon = IconImage.SilkAccept, String text = null, Orientation orientation = Orientation.Horizontal, bool showDefaultBackground = false, string toolTip = null, int minWidth = 0, int? column = null, int? row = null, int? columnSpan = 1, int? rowSpan = 1) { return toolbar.AddButton( id, icon.ToImage(), text, orientation, showDefaultBackground, toolTip, minWidth, column, row, columnSpan, rowSpan); }
/// <summary> /// Process touch completed events /// </summary> /// <param name="e"></param> /// <param name="outputVerbose"></param> async void ProcessCompletedTouchEvent(SkiaSharp.Views.Forms.SKTouchEventArgs e, bool outputVerbose = false) { if (canvas.Icons[canvas.Icons.IndexOf(emitterReference)].IsPressed) { canvas.Icons[canvas.Icons.IndexOf(emitterReference)].IsPressed = false; canvas.InvalidateSurface(); } // If out of scope, return if (_currentIcon == null) { return; } switch (_currentIcon.Tag) { case (int)IconRoles.Role.Communication: if (canvas.Controller.InEditMode && !hasMoved) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Completed icon tap"); if (App.InstanceModificationPage == null) { App.InstanceModificationPage = new ModifyPage(_currentIcon, canvas.Controller); } else { App.InstanceModificationPage.UpdateCurrentIcon(_currentIcon); } await Navigation.PushPopupAsync(App.InstanceModificationPage); } else if (canvas.Controller.InEditMode && !_currentIcon.IsInsertableIntoFolder && System.DateTime.Now.Subtract(itemPressTime).Seconds > 3) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Completed icon held > 3s"); if (App.InstanceModificationPage == null) { App.InstanceModificationPage = new ModifyPage(_currentIcon, canvas.Controller); } else { App.InstanceModificationPage.UpdateCurrentIcon(_currentIcon); } await Navigation.PushPopupAsync(App.InstanceModificationPage); } else if (hasMoved && _currentIcon.IsInsertableIntoFolder) { OutputDebug("Icon completed, has moved"); var folderOfInterest = GetFoldersOfInterest(); App.UserInputInstance.InsertIntoFolder(_currentIcon: _currentIcon, folderOfInterest: folderOfInterest); } e.Handled = true; return; case (int)IconRoles.Role.Folder: if (canvas.Controller.InEditMode && !hasMoved) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Completed folder tap"); if (App.InstanceModificationPage == null) { App.InstanceModificationPage = new ModifyPage(_currentIcon, canvas.Controller); } else { App.InstanceModificationPage.UpdateCurrentIcon(_currentIcon); } await Navigation.PushPopupAsync(App.InstanceModificationPage); e.Handled = true; } else if (canvas.Controller.InEditMode && System.DateTime.Now.Subtract(itemPressTime).Seconds > 3) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Completed folder hold"); if (App.InstanceModificationPage == null) { App.InstanceModificationPage = new ModifyPage(_currentIcon, canvas.Controller); } else { App.InstanceModificationPage.UpdateCurrentIcon(_currentIcon); } await Navigation.PushPopupAsync(App.InstanceModificationPage); e.Handled = true; } if (!canvas.Controller.InEditMode && !hasMoved) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Hit a folder, in user mode: " + _currentIcon.Text); // This is where the current item is the folder in question var itemsMatching = GetItemsMatching(); // Leave if empty if (itemsMatching == null) { e.Handled = true; return; } if (App.InstanceStoredIconsViewModel == null) { App.InstanceStoredIconsViewModel = new ViewModels.StoredIconPopupViewModel { Padding = new Xamarin.Forms.Thickness(100, 100, 100, 100), IsSystemPadding = true, FolderWithIcons = _currentIcon.Text, ItemsMatching = itemsMatching, }; App.InstanceStoredIconsViewModel.IconSelected += RestoreIcon; App.InstanceStoredIconPage = new StoredIconPopup() { BindingContext = App.InstanceStoredIconsViewModel }; } else { App.InstanceStoredIconsViewModel.FolderWithIcons = _currentIcon.Text; App.InstanceStoredIconsViewModel.ItemsMatching = itemsMatching; } await Xamarin.Forms.Application.Current.MainPage.Navigation.PushPopupAsync(App.InstanceStoredIconPage); e.Handled = true; } else if (!canvas.Controller.InEditMode && System.DateTime.Now.Subtract(itemPressTime).Seconds > 3) { if (App.UserInputInstance.AreModalsOpen()) { return; } OutputDebug("Held a folder, in user mode: " + _currentIcon.Text); // This is where the current item is the folder in question var itemsMatching = GetItemsMatching(); // Leave if empty if (itemsMatching == null) { e.Handled = true; return; } if (App.InstanceStoredIconsViewModel == null) { App.InstanceStoredIconsViewModel = new ViewModels.StoredIconPopupViewModel { Padding = new Xamarin.Forms.Thickness(100, 100, 100, 100), IsSystemPadding = true, FolderWithIcons = _currentIcon.Text, ItemsMatching = itemsMatching, }; App.InstanceStoredIconsViewModel.IconSelected += RestoreIcon; App.InstanceStoredIconPage = new StoredIconPopup() { BindingContext = App.InstanceStoredIconsViewModel }; } else { App.InstanceStoredIconsViewModel.FolderWithIcons = _currentIcon.Text; App.InstanceStoredIconsViewModel.ItemsMatching = itemsMatching; } await Xamarin.Forms.Application.Current.MainPage.Navigation.PushPopupAsync(App.InstanceStoredIconPage); e.Handled = true; } return; default: // Emitter was tapped/held if (holdingEmitter) { holdingEmitter = false; OutputDebug("Seconds held: " + (System.DateTime.Now - emitterPressTime).TotalSeconds.ToString()); OutputDebug("Bottom Oriented: " + canvas.Controller.InFramedModeBottom); // Enter into Edit Mode if ((System.DateTime.Now - emitterPressTime).Seconds >= thresholdAdmin && !canvas.Controller.InEditMode) { canvas.Controller.UpdateSettings(isEditing: !canvas.Controller.InEditMode, isInFrame: canvas.Controller.InFramedMode, isFrameBottom: canvas.Controller.InFramedModeBottom, isAutoDeselecting: canvas.Controller.RequireDeselect, isInIconModeAuto: canvas.Controller.IconModeAuto); canvas.Controller.BackgroundColor = canvas.Controller.InEditMode ? SKColors.DarkOrange : SKColors.DimGray; resource = App.BoardSettings.InEditMode ? "FastTalkerSkiaSharp.Images.Settings.png" : "FastTalkerSkiaSharp.Images.Speaker.png"; if (canvas.Controller.InFramedModeBottom && canvas.Controller.InFramedMode) { var list = canvas.Icons.Where(elem => elem.Tag == IconRoles.GetRoleInt(IconRoles.Role.Emitter)).ToList(); foreach (var icon in list) { canvas.Icons.Remove(icon); } emitterReference = App.ImageBuilderInstance.BuildStaticIconBottom(resource: resource, xPercent: 2f, yPercent: 1.5f, tag: IconRoles.GetRoleInt(IconRoles.Role.Emitter)); canvas.Icons.Add(emitterReference); } else { var list = canvas.Icons.Where(elem => elem.Tag == IconRoles.GetRoleInt(IconRoles.Role.Emitter)).ToList(); foreach (var icon in list) { canvas.Icons.Remove(icon); } emitterReference = App.ImageBuilderInstance.BuildStaticIcon(resource: resource, xPercent: 2f, yPercent: 1.5f, tag: IconRoles.GetRoleInt(IconRoles.Role.Emitter)); canvas.Icons.Add(emitterReference); } SendReferenceToBack(emitterReference); ClearIconsInPlay(); } // TODO: Fix exit program (changed since emitter fx altered) else if ((System.DateTime.Now - emitterPressTime).Seconds >= thresholdReset && canvas.Controller.InEditMode) { // TODO: Confirm message? OutputDebug("In reset hook, returning to home"); Xamarin.Forms.Application.Current.MainPage = new TitlePage(); } // Speak output else { if (canvas.Controller.InFramedMode) { var mIntersectingIcons = GetSentenceContent(); if (mIntersectingIcons != null && mIntersectingIcons.Count() > 0) { var output = System.String.Join(" ", mIntersectingIcons); OutputDebug("Verbal output (Frame): " + output); commInterface.SpeakText(text: output); } } else if (!canvas.Controller.IconModeAuto) { var selectedIcons = GetMainIconInPlay(); if (selectedIcons != null) { OutputDebug("Verbal output (Icon): " + selectedIcons); commInterface.SpeakText(text: selectedIcons); } if (canvas.Controller.RequireDeselect) { ClearIconsInPlay(); } } } e.Handled = true; } return; } }
bool IsLowQuality(IconImage iconImage) { return(iconImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format1bppIndexed || iconImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format4bppIndexed || iconImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed); }
public IconiOSCell(string cellId, IconTextCell cell) : base(UITableViewCellStyle.Default, cellId) { NativeCell = cell; SelectionStyle = cell.SelectionStyle.ToiOSSelectionStyle(); var code = cell.IconCode; // Icon code is mapped by a converter further up the chain. It is managed by binding from the cell factory. if (!string.IsNullOrWhiteSpace(code)) { IconImage = new UIImageView(UIImage.FromFile(code)); } else { IconImage = new UIImageView(); } TextContainer = new UIStackView(); TextContainer.Axis = UILayoutConstraintAxis.Vertical; TextContainer.TranslatesAutoresizingMaskIntoConstraints = false; TextContainer.Alignment = UIStackViewAlignment.Fill; HeadingLabel = new UILabel() { BackgroundColor = UIColor.Clear, TextColor = UIColor.Black, Font = UIFont.PreferredBody, }; DetailLabel = new UILabel() { BackgroundColor = UIColor.Clear, TextColor = UIColor.Black, Font = UIFont.PreferredSubheadline, }; ContentView.Add(IconImage); ContentView.Add(TextContainer); TextContainer.AddArrangedSubview(HeadingLabel); if (cell.DisplayMode != Redbridge.Forms.ViewModels.Cells.IconCellViewMode.TitleOnly) { TextContainer.AddArrangedSubview(DetailLabel); } switch (cell.CellHeight) { case TableCellHeight.Large: IconImage.AddWidthAndHeightConstraints(32, 32); this.AddLeftConstraint(IconImage, 15); break; case TableCellHeight.Medium: IconImage.AddWidthAndHeightConstraints(24, 24); this.AddLeftConstraint(IconImage, 10); break; default: IconImage.AddWidthAndHeightConstraints(16, 16); this.AddLeftConstraint(IconImage, 5); break; } this.AddVerticalAlignmentConstraint(IconImage); this.AddVerticalAlignmentConstraint(TextContainer); this.AddLeftMarginConstraintBetween(IconImage, TextContainer, 5); HeadingLabel.AddHeightConstraint(16); DetailLabel.AddHeightConstraint(16); }
private void InitFromStreamWithSize(Stream stream, int width, int height) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (stream.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(stream))); } bool sizeObtained = false; ushort dirEntryCount; // Read the icon header using (var reader = new BinaryReader(stream)) { iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 { throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(stream))); } iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 { throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(stream))); } dirEntryCount = reader.ReadUInt16(); imageData = new ImageData[dirEntryCount]; iconDir.idCount = dirEntryCount; iconDir.idEntries = new IconDirEntry[dirEntryCount]; // Now read in the IconDirEntry structures for (int i = 0; i < dirEntryCount; i++) { var ide = new IconDirEntry { width = reader.ReadByte(), height = reader.ReadByte(), colorCount = reader.ReadByte(), reserved = reader.ReadByte(), planes = reader.ReadUInt16(), bitCount = reader.ReadUInt16(), bytesInRes = reader.ReadUInt32(), imageOffset = reader.ReadUInt32() }; // Vista 256x256 icons points directly to a PNG bitmap // 256x256 icons are decoded as 0x0 (width and height are encoded as BYTE) // We mark them as png and later on we just store the raw bytes to be able to save to a file. ide.png = (ide.width == 0) && (ide.height == 0); iconDir.idEntries[i] = ide; if (!sizeObtained) { if (((ide.height == height) || (ide.width == width)) && !ide.png) { this.id = (ushort)i; sizeObtained = true; this.iconSize.Height = ide.height; this.iconSize.Width = ide.width; } } } // If we havent found the best match, return the one with the largest size. if (!sizeObtained) { uint largestSize = 0; for (int j = 0; j < dirEntryCount; j++) { if (iconDir.idEntries[j].bytesInRes >= largestSize && !iconDir.idEntries[j].png) { largestSize = iconDir.idEntries[j].bytesInRes; this.id = (ushort)j; this.iconSize.Height = iconDir.idEntries[j].height; this.iconSize.Width = iconDir.idEntries[j].width; } } } // Now read in the icon data bool valid = false; for (int j = 0; j < dirEntryCount; j++) { stream.Seek(iconDir.idEntries[j].imageOffset, SeekOrigin.Begin); byte[] buffer = new byte[iconDir.idEntries[j].bytesInRes]; stream.Read(buffer, 0, buffer.Length); using (var bihReader = new BinaryReader(new MemoryStream(buffer))) { uint headerSize = bihReader.ReadUInt32(); int headerWidth = bihReader.ReadInt32(); // Process PNG images into IconDump if (iconDir.idEntries[j].png || (headerSize == PNGSignature1 && headerWidth == (int)PNGSignature2)) { IconDump id = new IconDump(); id.data = buffer; imageData[j] = id; iconDir.idEntries[j].png = true; continue; } // We found a valid icon BMP entry. valid = true; var bih = new BitmapInfoHeader { biSize = headerSize, biWidth = headerWidth, biHeight = bihReader.ReadInt32(), biPlanes = bihReader.ReadUInt16(), biBitCount = bihReader.ReadUInt16(), biCompression = bihReader.ReadUInt32(), biSizeImage = bihReader.ReadUInt32(), biXPelsPerMeter = bihReader.ReadInt32(), biYPelsPerMeter = bihReader.ReadInt32(), biClrUsed = bihReader.ReadUInt32(), biClrImportant = bihReader.ReadUInt32() }; var iidata = new IconImage { iconHeader = bih }; // Read the number of colors used and corresponding memory occupied by // color table. Fill this memory chunk into rgbquad[] int numColors; switch (bih.biBitCount) { case 1: numColors = 2; break; case 4: numColors = 16; break; case 8: numColors = 256; break; default: numColors = 0; break; } iidata.iconColors = new uint[numColors]; for (int i = 0; i < numColors; i++) { iidata.iconColors[i] = bihReader.ReadUInt32(); } //XOR mask is immediately after ColorTable and its size is //icon height* no. of bytes per line //icon height is half of BITMAPINFOHEADER.biHeight, since it contains //both XOR as well as AND mask bytes int iconHeight = bih.biHeight / 2; //bytes per line should be uint aligned int numBytesPerLine = checked ((((bih.biWidth * bih.biPlanes * bih.biBitCount) + 31) >> 5) << 2); //Determine the XOR array Size int xorSize = checked (numBytesPerLine * iconHeight); iidata.iconXOR = new byte[xorSize]; int nread = bihReader.Read(iidata.iconXOR, 0, xorSize); if (nread != xorSize) { throw new ArgumentException(SR.Format(SR.IconInvalidMaskLength, "XOR", xorSize, nread), nameof(stream)); } //Determine the AND array size numBytesPerLine = checked ((((bih.biWidth) + 31) & ~31) >> 3); int andSize = checked (numBytesPerLine * iconHeight); iidata.iconAND = new byte[andSize]; nread = bihReader.Read(iidata.iconAND, 0, andSize); if (nread != andSize) { throw new ArgumentException(SR.Format(SR.IconInvalidMaskLength, "AND", andSize, nread), nameof(stream)); } imageData[j] = iidata; } } // Throw error if no valid entries found if (!valid) { throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER, SR.Format(SR.InvalidPictureType, "picture", nameof(stream))); } } }
/// <summary> /// Builds the communication folder local. /// </summary> /// <returns>The communication folder local.</returns> /// <param name="icon">Icon.</param> public IconImage BuildCommunicationFolderLocal(Storage.CommunicationIcon icon) { IconImage image = null; SKSize loadedSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, icon.Scale, icon.Scale); using (System.IO.Stream stream = App.MainAssembly.GetManifestResourceStream(icon.ResourceLocation)) { SKBitmap tempBitmapPre = SKBitmap.Decode(stream); SKBitmap tempBitmap = tempBitmapPre.Resize(new SKImageInfo((int)loadedSize.Width, (int)loadedSize.Width), SKBitmapResizeMethod.Lanczos3); SKBitmap returnBitmap = new SKBitmap((int)System.Math.Round(tempBitmap.Width * 1.5), (int)System.Math.Round(tempBitmap.Height * 1.5), tempBitmap.ColorType, tempBitmap.AlphaType); using (SKCanvas canvas2 = new SKCanvas(returnBitmap)) { canvas2.Clear(SKColors.Transparent); canvas2.DrawBitmap(tempBitmap, SKRect.Create(System.Convert.ToInt16(tempBitmap.Width * 0.15), System.Convert.ToInt16(tempBitmap.Height * 0.1), tempBitmap.Width * 1.3f, tempBitmap.Height * 1.3f)); using (SKPaint paint = new SKPaint()) { paint.TextSize = Constants.DeviceLayout.TextSizeDefault * App.DisplayScaleFactor * icon.Scale; paint.IsAntialias = true; paint.Color = SKColors.White; paint.TextAlign = SKTextAlign.Center; canvas2.DrawText(icon.Text, (System.Convert.ToSingle(tempBitmap.Width) * 1.5f) / 2f, (System.Convert.ToSingle(tempBitmap.Height) * 1.5f) - (System.Convert.ToSingle(tempBitmap.Height) * 1.5f) / 4f, paint); } canvas2.Flush(); } SKSize finalSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, Constants.DeviceLayout.InterfaceDimensionDefault, Constants.DeviceLayout.InterfaceDimensionDefault); SKPoint settingsPoint; if ((int)icon.X == -1 || (int)icon.Y == -1) { settingsPoint = Constants.DeviceLayout.GetCenterPoint(canvasReference.CanvasSize); } else { settingsPoint = new SKPoint(icon.X, icon.Y); } image = new IconImage(returnBitmap) { Tag = icon.Tag, Text = icon.Text, ImageInformation = icon.ResourceLocation, LocalImage = true, IsInsertableIntoFolder = false, IsPinnedToSpot = icon.IsPinned, StoredFolderTag = icon.FolderContainingIcon, IsStoredInAFolder = icon.IsStoredInFolder, CurrentScale = icon.Scale, BorderColor = SKColors.Black, BorderWidth = 2f, Bounds = SKRect.Create(settingsPoint, loadedSize) }; return(image); } }
internal Bitmap BuildBitmapOnWin32() { Bitmap bmp; if (imageData == null) { return(new Bitmap(32, 32)); } IconImage ii = (IconImage)imageData[id]; BitmapInfoHeader bih = ii.iconHeader; int biHeight = bih.biHeight / 2; int ncolors = (int)bih.biClrUsed; if ((ncolors == 0) && (bih.biBitCount < 24)) { ncolors = (int)(1 << bih.biBitCount); } switch (bih.biBitCount) { case 1: bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format1bppIndexed); break; case 4: bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format4bppIndexed); break; case 8: bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format8bppIndexed); break; case 24: bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format24bppRgb); break; case 32: bmp = new Bitmap(bih.biWidth, biHeight, PixelFormat.Format32bppArgb); break; default: string msg = string.Format("Unexpected number of bits: {0}", bih.biBitCount); throw new Exception(msg); } if (bih.biBitCount < 24) { ColorPalette pal = bmp.Palette; // Managed palette for (int i = 0; i < ii.iconColors.Length; i++) { pal.Entries[i] = Color.FromArgb((int)ii.iconColors[i] | unchecked ((int)0xff000000)); } bmp.Palette = pal; } int bytesPerLine = (int)((((bih.biWidth * bih.biBitCount) + 31) & ~31) >> 3); BitmapData bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); for (int y = 0; y < biHeight; y++) { Marshal.Copy(ii.iconXOR, bytesPerLine * y, (IntPtr)(bits.Scan0.ToInt64() + bits.Stride * (biHeight - 1 - y)), bytesPerLine); } bmp.UnlockBits(bits); bmp = new Bitmap(bmp); // This makes a 32bpp image out of an indexed one // Apply the mask to make properly transparent bytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3); for (int y = 0; y < biHeight; y++) { for (int x = 0; x < bih.biWidth / 8; x++) { for (int bit = 7; bit >= 0; bit--) { if (((ii.iconAND[y * bytesPerLine + x] >> bit) & 1) != 0) { bmp.SetPixel(x * 8 + 7 - bit, biHeight - y - 1, Color.Transparent); } } } } return(bmp); }
public bool Equals(DestinyHistoricalStatsDefinition input) { if (input == null) { return(false); } return (( StatId == input.StatId || (StatId != null && StatId.Equals(input.StatId)) ) && ( Group == input.Group || (Group != null && Group.Equals(input.Group)) ) && ( PeriodTypes == input.PeriodTypes || (PeriodTypes != null && PeriodTypes.SequenceEqual(input.PeriodTypes)) ) && ( Modes == input.Modes || (Modes != null && Modes.SequenceEqual(input.Modes)) ) && ( Category == input.Category || (Category != null && Category.Equals(input.Category)) ) && ( StatName == input.StatName || (StatName != null && StatName.Equals(input.StatName)) ) && ( StatNameAbbr == input.StatNameAbbr || (StatNameAbbr != null && StatNameAbbr.Equals(input.StatNameAbbr)) ) && ( StatDescription == input.StatDescription || (StatDescription != null && StatDescription.Equals(input.StatDescription)) ) && ( UnitType == input.UnitType || (UnitType != null && UnitType.Equals(input.UnitType)) ) && ( IconImage == input.IconImage || (IconImage != null && IconImage.Equals(input.IconImage)) ) && ( MergeMethod == input.MergeMethod || (MergeMethod.Equals(input.MergeMethod)) ) && ( UnitLabel == input.UnitLabel || (UnitLabel != null && UnitLabel.Equals(input.UnitLabel)) ) && ( Weight == input.Weight || (Weight.Equals(input.Weight)) ) && ( MedalTierHash == input.MedalTierHash || (MedalTierHash.Equals(input.MedalTierHash)) )); }
private void WindowLoaded(object sender, RoutedEventArgs e) { _mainViewModel = DataContext as MainViewModel; _mainViewModel.AnnoCanvas = annoCanvas; App.DpiScale = VisualTreeHelper.GetDpi(this); _instance = this; // add event handlers annoCanvas.OnCurrentObjectChanged += UpdateUIFromObject; annoCanvas.OnStatusMessageChanged += StatusMessageChanged; annoCanvas.OnLoadedFileChanged += LoadedFileChanged; annoCanvas.OnClipboardChanged += ClipboardChanged; DpiChanged += MainWindow_DpiChanged; foreach (MenuItem item in LanguageMenu.Items) { if (item.Header.ToString() == SelectedLanguage) { item.IsChecked = true; } } LoadSettings(); // add icons to the combobox comboBoxIcon.Items.Clear(); _noIconItem = new IconImage("None"); comboBoxIcon.Items.Add(_noIconItem); foreach (var icon in annoCanvas.Icons) { comboBoxIcon.Items.Add(icon.Value); } comboBoxIcon.SelectedIndex = 0; _mainViewModel.VersionValue = Constants.Version.ToString("0.0#", CultureInfo.InvariantCulture); _mainViewModel.FileVersionValue = CoreConstants.LayoutFileVersion.ToString("0.#", CultureInfo.InvariantCulture); // check for updates on startup CheckForUpdates(false);//just fire and forget // load color presets colorPicker.StandardColors.Clear(); //This is currently disabled colorPicker.ShowStandardColors = false; //try //{ // ColorPresetsLoader loader = new ColorPresetsLoader(); // var defaultScheme = loader.LoadDefaultScheme(); // foreach (var curPredefinedColor in defaultScheme.Colors.GroupBy(x => x.Color).Select(x => x.Key)) // { // //colorPicker.StandardColors.Add(new Xceed.Wpf.Toolkit.ColorItem(curPredefinedColor.Color, $"{curPredefinedColor.TargetTemplate}")); // colorPicker.StandardColors.Add(new Xceed.Wpf.Toolkit.ColorItem(curPredefinedColor, curPredefinedColor.ToHex())); // } //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message, "Loading of the color presets failed"); //} // load presets BuildingPresets presets = annoCanvas.BuildingPresets; if (presets != null) { GroupBoxPresets.Header = string.Format("Building presets - loaded v{0}", presets.Version); _mainViewModel.PresetsVersionValue = presets.Version; _mainViewModel.PresetsTreeViewModel.ApplySelectedItem += PresetTreeViewModel_ApplySelectedItem; _mainViewModel.PresetsTreeViewModel.LoadItems(annoCanvas.BuildingPresets); //apply saved search before restoring state if (!string.IsNullOrWhiteSpace(Settings.Default.TreeViewSearchText)) { _mainViewModel.PresetsTreeViewModel.FilterText = Settings.Default.TreeViewSearchText; } if (!string.IsNullOrWhiteSpace(Settings.Default.PresetsTreeExpandedState)) { Dictionary <int, bool> savedTreeState = null; using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(Settings.Default.PresetsTreeExpandedState))) { savedTreeState = SerializationHelper.LoadFromStream <Dictionary <int, bool> >(ms); } _mainViewModel.PresetsTreeViewModel.SetCondensedTreeState(savedTreeState, Settings.Default.PresetsTreeLastVersion); } } else { GroupBoxPresets.Header = "Building presets - load failed"; } // load file given by argument if (!string.IsNullOrEmpty(App.FilenameArgument)) { annoCanvas.OpenFile(App.FilenameArgument); } }
private void RebuildIcon() { //// If we have are a connected destination endpoint then we have to procedurally build //// an arrow-head polygon //if (EndpointType.StreamDestinationConnected == m_type) //{ // AbstractStream a = m_owner as AbstractStream; // // Get the points array for the arrow's vertices // Point[] pts = a.GetArrowVertices(); // double minX, minY, maxX, maxY; // minX = minY = double.MaxValue; // maxX = maxY = double.MinValue; // foreach (Point pt in pts) // { // minX = Math.Min(minX, pt.X); // minY = Math.Min(minY, pt.Y); // maxX = Math.Max(maxX, pt.X); // maxY = Math.Max(maxY, pt.Y); // } // // Set the width and height // Width = maxX - minX; // Height = maxY - minY; // // Adjust points to make them relative to this control's coordinate system // for (int i = 0; i < 3; i++) // { // ArrowIcon.Points[i] = new Point(pts[i].X - minX, pts[i].Y - minY); // } // // Want position such that: // // Left.X + (pts[0].X - minX) = pts[0].X // // Left.X = minX // // Similar thing for Y // SetValue(Canvas.LeftProperty, minX); // SetValue(Canvas.TopProperty, minY); // // Use the same fill as the stem // ArrowIcon.Fill = m_owner.Stem.Fill; // // Make sure it's visible and the icon is hidden // ArrowIcon.Visibility = System.Windows.Visibility.Visible; // IconImage.Visibility = System.Windows.Visibility.Collapsed; // // Tell the other endpoint to update since we have potentially just repositioned this one // OtherEndpoint.PU_LocationChanged(null, null); //} //else if (true) { BitmapImage bmp = new BitmapImage(); // We have an icon for each of these 3 types switch (m_type) { case EndpointType.StreamDestination: bmp.UriSource = new Uri("/UI/Icons/pu_sink.png", UriKind.Relative); Width = Height = 20; break; //case EndpointType.StreamSourceConnected: // bmp.UriSource = new Uri("/UI/Icons/StreamSourceConnection.png", UriKind.Relative); // Width = Height = 12; // break; case EndpointType.StreamSource: bmp.UriSource = new Uri("/UI/Icons/pu_source.png", UriKind.Relative); Width = Height = 20; break; default: // Should be impossible to get here (unless breaking changes are made to this code) throw new InvalidOperationException(); } // Set the icon image IconImage.SetValue(Image.SourceProperty, bmp); IconImage.Visibility = System.Windows.Visibility.Visible; // Make sure the arrow is hidden ArrowIcon.Visibility = System.Windows.Visibility.Collapsed; } }
private void InitFromStreamWithSize (Stream stream, int width, int height) { //read the icon header if (stream == null || stream.Length == 0) throw new System.ArgumentException ("The argument 'stream' must be a picture that can be used as a Icon", "stream"); BinaryReader reader = new BinaryReader (stream); //iconDir = new IconDir (); iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 throw new System.ArgumentException ("Invalid Argument", "stream"); iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 throw new System.ArgumentException ("Invalid Argument", "stream"); ushort dirEntryCount = reader.ReadUInt16(); iconDir.idCount = dirEntryCount; iconDir.idEntries = new IconDirEntry [dirEntryCount]; imageData = new IconImage [dirEntryCount]; bool sizeObtained = false; //now read in the IconDirEntry structures for (int i=0; i<dirEntryCount; i++){ IconDirEntry ide; ide.width = reader.ReadByte (); ide.height = reader.ReadByte (); ide.colorCount = reader.ReadByte (); ide.reserved = reader.ReadByte (); ide.planes = reader.ReadUInt16 (); ide.bitCount = reader.ReadUInt16 (); ide.bytesInRes = reader.ReadUInt32 (); ide.imageOffset = reader.ReadUInt32 (); iconDir.idEntries [i] = ide; //is this is the best fit?? if (!sizeObtained) if (ide.height==height && ide.width==width) { this.id = (ushort) i; sizeObtained = true; this.iconSize.Height = ide.height; this.iconSize.Width = ide.width; } } //if we havent found the best match, return the one with the //largest size. Is this approach correct?? if (!sizeObtained){ uint largestSize = 0; for (int j=0; j<dirEntryCount; j++){ if (iconDir.idEntries [j].bytesInRes >= largestSize) { largestSize = iconDir.idEntries [j].bytesInRes; this.id = (ushort) j; this.iconSize.Height = iconDir.idEntries [j].height; this.iconSize.Width = iconDir.idEntries [j].width; } } } //now read in the icon data for (int j = 0; j<dirEntryCount; j++) { IconImage iidata = new IconImage(); BitmapInfoHeader bih = new BitmapInfoHeader(); stream.Seek (iconDir.idEntries [j].imageOffset, SeekOrigin.Begin); byte [] buffer = new byte [iconDir.idEntries [j].bytesInRes]; stream.Read (buffer, 0, buffer.Length); BinaryReader bihReader = new BinaryReader (new MemoryStream(buffer)); bih.biSize = bihReader.ReadUInt32 (); bih.biWidth = bihReader.ReadInt32 (); bih.biHeight = bihReader.ReadInt32 (); bih.biPlanes = bihReader.ReadUInt16 (); bih.biBitCount = bihReader.ReadUInt16 (); bih.biCompression = bihReader.ReadUInt32 (); bih.biSizeImage = bihReader.ReadUInt32 (); bih.biXPelsPerMeter = bihReader.ReadInt32 (); bih.biYPelsPerMeter = bihReader.ReadInt32 (); bih.biClrUsed = bihReader.ReadUInt32 (); bih.biClrImportant = bihReader.ReadUInt32 (); iidata.iconHeader = bih; //Read the number of colors used and corresponding memory occupied by //color table. Fill this memory chunk into rgbquad[] int numColors; switch (bih.biBitCount){ case 1: numColors = 2; break; case 4: numColors = 16; break; case 8: numColors = 256; break; default: numColors = 0; break; } iidata.iconColors = new uint [numColors]; for (int i=0; i<numColors; i++) iidata.iconColors [i] = bihReader.ReadUInt32 (); //XOR mask is immediately after ColorTable and its size is //icon height* no. of bytes per line //icon height is half of BITMAPINFOHEADER.biHeight, since it contains //both XOR as well as AND mask bytes int iconHeight = bih.biHeight/2; //bytes per line should should be uint aligned int numBytesPerLine = ((((bih.biWidth * bih.biPlanes * bih.biBitCount)+ 31)>>5)<<2); //Determine the XOR array Size int xorSize = numBytesPerLine * iconHeight; iidata.iconXOR = new byte [xorSize]; for (int i=0; i<xorSize; i++) iidata.iconXOR[i] = bihReader.ReadByte(); //Determine the AND array size //For this i subtract the current position from the length. //ugly hack... int andSize = (int) (bihReader.BaseStream.Length - bihReader.BaseStream.Position); iidata.iconAND = new byte [andSize]; for (int i=0; i<andSize; i++) iidata.iconAND[i] = bihReader.ReadByte(); imageData [j] = iidata; bihReader.Close(); } reader.Close(); }
private void SaveIconImage (BinaryWriter writer, IconImage ii) { BitmapInfoHeader bih = ii.iconHeader; writer.Write (bih.biSize); writer.Write (bih.biWidth); writer.Write (bih.biHeight); writer.Write (bih.biPlanes); writer.Write (bih.biBitCount); writer.Write (bih.biCompression); writer.Write (bih.biSizeImage); writer.Write (bih.biXPelsPerMeter); writer.Write (bih.biYPelsPerMeter); writer.Write (bih.biClrUsed); writer.Write (bih.biClrImportant); //now write color table int colCount = ii.iconColors.Length; for (int j=0; j < colCount; j++) writer.Write (ii.iconColors [j]); //now write XOR Mask writer.Write (ii.iconXOR); //now write AND Mask writer.Write (ii.iconAND); }
private void InitFromStreamWithSize (Stream stream, int width, int height) { //read the icon header if (stream == null || stream.Length == 0) throw new System.ArgumentException ("The argument 'stream' must be a picture that can be used as a Icon", "stream"); BinaryReader reader = new BinaryReader (stream); //iconDir = new IconDir (); iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 throw new System.ArgumentException ("Invalid Argument", "stream"); iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 throw new System.ArgumentException ("Invalid Argument", "stream"); ushort dirEntryCount = reader.ReadUInt16(); ArrayList entries = new ArrayList (dirEntryCount); bool sizeObtained = false; // now read in the IconDirEntry structures for (int i = 0; i < dirEntryCount; i++) { IconDirEntry ide; ide.width = reader.ReadByte (); ide.height = reader.ReadByte (); ide.colorCount = reader.ReadByte (); ide.reserved = reader.ReadByte (); ide.planes = reader.ReadUInt16 (); ide.bitCount = reader.ReadUInt16 (); ide.bytesInRes = reader.ReadUInt32 (); ide.imageOffset = reader.ReadUInt32 (); #if false Console.WriteLine ("Entry: {0}", i); Console.WriteLine ("\tide.width: {0}", ide.width); Console.WriteLine ("\tide.height: {0}", ide.height); Console.WriteLine ("\tide.colorCount: {0}", ide.colorCount); Console.WriteLine ("\tide.reserved: {0}", ide.reserved); Console.WriteLine ("\tide.planes: {0}", ide.planes); Console.WriteLine ("\tide.bitCount: {0}", ide.bitCount); Console.WriteLine ("\tide.bytesInRes: {0}", ide.bytesInRes); Console.WriteLine ("\tide.imageOffset: {0}", ide.imageOffset); #endif // 256x256 icons are decoded as 0x0 (width and height are encoded as BYTE) // and we ignore them just like MS does (at least up to fx 2.0) if ((ide.width == 0) && (ide.height == 0)) continue; int index = entries.Add (ide); //is this is the best fit?? if (!sizeObtained) { if ((ide.height == height) || (ide.width == width)) { this.id = (ushort) index; sizeObtained = true; this.iconSize.Height = ide.height; this.iconSize.Width = ide.width; } } } // Vista 256x256 icons points directly to a PNG bitmap dirEntryCount = (ushort) entries.Count; if (dirEntryCount == 0) throw new Win32Exception (0, "No valid icon entry were found."); iconDir.idCount = dirEntryCount; imageData = new IconImage [dirEntryCount]; iconDir.idEntries = new IconDirEntry [dirEntryCount]; entries.CopyTo (iconDir.idEntries); //if we havent found the best match, return the one with the //largest size. Is this approach correct?? if (!sizeObtained){ uint largestSize = 0; for (int j=0; j<dirEntryCount; j++){ if (iconDir.idEntries [j].bytesInRes >= largestSize) { largestSize = iconDir.idEntries [j].bytesInRes; this.id = (ushort) j; this.iconSize.Height = iconDir.idEntries [j].height; this.iconSize.Width = iconDir.idEntries [j].width; } } } //now read in the icon data for (int j = 0; j<dirEntryCount; j++) { IconImage iidata = new IconImage(); BitmapInfoHeader bih = new BitmapInfoHeader(); stream.Seek (iconDir.idEntries [j].imageOffset, SeekOrigin.Begin); byte [] buffer = new byte [iconDir.idEntries [j].bytesInRes]; stream.Read (buffer, 0, buffer.Length); BinaryReader bihReader = new BinaryReader (new MemoryStream(buffer)); bih.biSize = bihReader.ReadUInt32 (); bih.biWidth = bihReader.ReadInt32 (); bih.biHeight = bihReader.ReadInt32 (); bih.biPlanes = bihReader.ReadUInt16 (); bih.biBitCount = bihReader.ReadUInt16 (); bih.biCompression = bihReader.ReadUInt32 (); bih.biSizeImage = bihReader.ReadUInt32 (); bih.biXPelsPerMeter = bihReader.ReadInt32 (); bih.biYPelsPerMeter = bihReader.ReadInt32 (); bih.biClrUsed = bihReader.ReadUInt32 (); bih.biClrImportant = bihReader.ReadUInt32 (); #if false Console.WriteLine ("Entry: {0}", j); Console.WriteLine ("\tbih.biSize: {0}", bih.biSize); Console.WriteLine ("\tbih.biWidth: {0}", bih.biWidth); Console.WriteLine ("\tbih.biHeight: {0}", bih.biHeight); Console.WriteLine ("\tbih.biPlanes: {0}", bih.biPlanes); Console.WriteLine ("\tbih.biBitCount: {0}", bih.biBitCount); Console.WriteLine ("\tbih.biCompression: {0}", bih.biCompression); Console.WriteLine ("\tbih.biSizeImage: {0}", bih.biSizeImage); Console.WriteLine ("\tbih.biXPelsPerMeter: {0}", bih.biXPelsPerMeter); Console.WriteLine ("\tbih.biYPelsPerMeter: {0}", bih.biYPelsPerMeter); Console.WriteLine ("\tbih.biClrUsed: {0}", bih.biClrUsed); Console.WriteLine ("\tbih.biClrImportant: {0}", bih.biClrImportant); #endif iidata.iconHeader = bih; //Read the number of colors used and corresponding memory occupied by //color table. Fill this memory chunk into rgbquad[] int numColors; switch (bih.biBitCount){ case 1: numColors = 2; break; case 4: numColors = 16; break; case 8: numColors = 256; break; default: numColors = 0; break; } iidata.iconColors = new uint [numColors]; for (int i=0; i<numColors; i++) iidata.iconColors [i] = bihReader.ReadUInt32 (); //XOR mask is immediately after ColorTable and its size is //icon height* no. of bytes per line //icon height is half of BITMAPINFOHEADER.biHeight, since it contains //both XOR as well as AND mask bytes int iconHeight = bih.biHeight/2; //bytes per line should should be uint aligned int numBytesPerLine = ((((bih.biWidth * bih.biPlanes * bih.biBitCount)+ 31)>>5)<<2); //Determine the XOR array Size int xorSize = numBytesPerLine * iconHeight; iidata.iconXOR = new byte [xorSize]; int nread = bihReader.Read (iidata.iconXOR, 0, xorSize); if (nread != xorSize) { string msg = Locale.GetText ("{0} data length expected {1}, read {2}", "XOR", xorSize, nread); throw new ArgumentException (msg, "stream"); } //Determine the AND array size numBytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3); int andSize = numBytesPerLine * iconHeight; iidata.iconAND = new byte [andSize]; nread = bihReader.Read (iidata.iconAND, 0, andSize); if (nread != andSize) { string msg = Locale.GetText ("{0} data length expected {1}, read {2}", "AND", andSize, nread); throw new ArgumentException (msg, "stream"); } imageData [j] = iidata; bihReader.Close(); } reader.Close(); }
private void inicializarComponente(string descricao) { _Descricao = new Label { Style = Estilo.Estilo.Current[Estilo.Estilo.TITULO3], Text = descricao, HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, HorizontalTextAlignment = TextAlignment.Center }; _1Estrela = new IconImage { Icon = "fa-star-o", IconColor = Color.Gold, IconSize = 28 }; var tapGestureRecognizer1 = new TapGestureRecognizer(); tapGestureRecognizer1.Tapped += (sender, e) => { setEstrelas(1); }; _1Estrela.GestureRecognizers.Add(tapGestureRecognizer1); _2Estrela = new IconImage { Icon = "fa-star-o", IconColor = Color.Gold, IconSize = 28 }; var tapGestureRecognizer2 = new TapGestureRecognizer(); tapGestureRecognizer2.Tapped += (sender, e) => { setEstrelas(2); }; _2Estrela.GestureRecognizers.Add(tapGestureRecognizer2); _3Estrela = new IconImage { Icon = "fa-star-o", IconColor = Color.Gold, IconSize = 28 }; var tapGestureRecognizer3 = new TapGestureRecognizer(); tapGestureRecognizer3.Tapped += (sender, e) => { setEstrelas(3); }; _3Estrela.GestureRecognizers.Add(tapGestureRecognizer3); _4Estrela = new IconImage { Icon = "fa-star-o", IconColor = Color.Gold, IconSize = 28 }; var tapGestureRecognizer4 = new TapGestureRecognizer(); tapGestureRecognizer4.Tapped += (sender, e) => { setEstrelas(4); }; _4Estrela.GestureRecognizers.Add(tapGestureRecognizer4); _5Estrela = new IconImage { Icon = "fa-star-o", IconColor = Color.Gold, IconSize = 28 }; var tapGestureRecognizer5 = new TapGestureRecognizer(); tapGestureRecognizer5.Tapped += (sender, e) => { setEstrelas(5); }; _5Estrela.GestureRecognizers.Add(tapGestureRecognizer5); _ContainerEstrelas = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Start, Margin = new Thickness(0, 10, 0, 0), Children = { _1Estrela, _2Estrela, _3Estrela, _4Estrela, _5Estrela } }; _Confirmar = new Button() { Text = "Confirmar", HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, Style = Estilo.Estilo.Current[Estilo.Estilo.BTN_SUCESSO] }; _Confirmar.Clicked += (sender, e) => { if (Confirmed != null) { Confirmed(this, _Avaliacao); } Navigation.PopAsync(); }; }
private void SaveBitmapAsIcon(BinaryWriter writer) { writer.Write((ushort)0); // idReserved must be 0 writer.Write((ushort)1); // idType must be 1 writer.Write((ushort)1); // only one icon // when transformed into a bitmap only a single image exists IconDirEntry ide = new IconDirEntry(); ide.width = (byte)bitmap.Width; ide.height = (byte)bitmap.Height; ide.colorCount = 0; // 32 bbp == 0, for palette size ide.reserved = 0; // always 0 ide.planes = 0; ide.bitCount = 32; ide.imageOffset = 22; // 22 is the first icon position (for single icon files) BitmapInfoHeader bih = new BitmapInfoHeader(); bih.biSize = (uint)Marshal.SizeOf(typeof(BitmapInfoHeader)); bih.biWidth = bitmap.Width; bih.biHeight = 2 * bitmap.Height; // include both XOR and AND images bih.biPlanes = 1; bih.biBitCount = 32; bih.biCompression = 0; bih.biSizeImage = 0; bih.biXPelsPerMeter = 0; bih.biYPelsPerMeter = 0; bih.biClrUsed = 0; bih.biClrImportant = 0; IconImage ii = new IconImage(); ii.iconHeader = bih; ii.iconColors = Array.Empty <uint>(); // no palette int xor_size = (((bih.biBitCount * bitmap.Width + 31) & ~31) >> 3) * bitmap.Height; ii.iconXOR = new byte[xor_size]; int p = 0; for (int y = bitmap.Height - 1; y >= 0; y--) { for (int x = 0; x < bitmap.Width; x++) { Color c = bitmap.GetPixel(x, y); ii.iconXOR[p++] = c.B; ii.iconXOR[p++] = c.G; ii.iconXOR[p++] = c.R; ii.iconXOR[p++] = c.A; } } int and_line_size = (((Width + 31) & ~31) >> 3); // must be a multiple of 4 bytes int and_size = and_line_size * bitmap.Height; ii.iconAND = new byte[and_size]; ide.bytesInRes = (uint)(bih.biSize + xor_size + and_size); SaveIconDirEntry(writer, ide, UInt32.MaxValue); SaveIconImage(writer, ii); }
public void SetCommentObject(StickyNote comment, object parent) { if (null != m_sticky) { // Remove event handler before changing this value m_sticky.PropertyChanged -= this.StickyNote_PropertyChanged; } if (null != m_basic) { m_basic.OnTextChanged -= this.BasicComment_OnTextChanged; } // IMPORTANT: Unsubscribe from parent control property changes (if applicable) if (null != m_parentObject) { if (m_parentObject is AbstractProcessUnit) { (m_parentObject as AbstractProcessUnit).PropertyChanged -= this.ParentPU_PropertyChanged; } else if (m_parentObject is AbstractStream) { (m_parentObject as AbstractStream).PropertyChanged -= this.ParentStream_PropertyChanged; } } // Store references m_basic = null; m_sticky = comment; m_parentObject = parent; AbstractStream parentStream = parent as AbstractStream; AbstractProcessUnit parentAPU = parent as AbstractProcessUnit; // Update the UI elements if the comment is not null if (null != m_sticky) { CommentTextBox.Text = m_sticky.Text; UserNameLabel.Content = m_sticky.UserName; // Subsribe to property changes m_sticky.PropertyChanged += this.StickyNote_PropertyChanged; // Allow editing but not deletion CommentTextBox.IsReadOnly = false; XLabel.Visibility = System.Windows.Visibility.Collapsed; // Show or hide the icon based on the parent if (null != parentStream) { // Get the right icon for this type of stream string iconSource = PFD.Streams.StreamControl.GetIconSource(parent.GetType()); BitmapImage bmp = new BitmapImage(); bmp.UriSource = new Uri(iconSource, UriKind.Relative); IconImage.SetValue(Image.SourceProperty, bmp); // Make sure the icon is visible IconImage.Visibility = System.Windows.Visibility.Visible; TitleBarGrid.ColumnDefinitions[0].Width = new GridLength(20.0); // Give the icon a tooltip that tells what this is a comment for ToolTipService.SetToolTip(IconImage, "Comment for stream #" + parentStream.Id); // Subscribe to property changes for the stream parentStream.PropertyChanged += new PropertyChangedEventHandler(ParentStream_PropertyChanged); } else if (null != parentAPU) { // Get the right icon for this type of process unit string iconSource = ProcessUnitControl.GetIconSource(parent.GetType()); BitmapImage bmp = new BitmapImage(); bmp.UriSource = new Uri(iconSource, UriKind.Relative); IconImage.SetValue(Image.SourceProperty, bmp); // Make sure the icon is visible IconImage.Visibility = System.Windows.Visibility.Visible; TitleBarGrid.ColumnDefinitions[0].Width = new GridLength(20.0); // Give the icon a tooltip that tells what this is a comment for ToolTipService.SetToolTip(IconImage, "Comment for " + (m_parentObject as AbstractProcessUnit).Label); // Subscribe to property changes for the process unit parentAPU.PropertyChanged += new PropertyChangedEventHandler(ParentPU_PropertyChanged); } else { // Make sure the icon is hidden IconImage.Visibility = System.Windows.Visibility.Collapsed; TitleBarGrid.ColumnDefinitions[0].Width = new GridLength(0.0); } } }
/* * private string getImagemCaminhao(int? codCaminhao) * { * switch (codCaminhao) * { * case 1: * return "Veiculo_01.png"; * case 2: * return "Veiculo_02.png"; * case 3: * return "Veiculo_03.png"; * case 4: * return "Veiculo_04.png"; * case 5: * return "Veiculo_05.png"; * case 6: * return "Veiculo_06.png"; * case 7: * return "Veiculo_07.png"; * case 8: * return "Veiculo_08.png"; * case 9: * return "Veiculo_09.png"; * default: * return "Veiculo_01.png"; * } * } */ private void inicializarComponente() { _Titulo = new Label { Text = _frete.TituloFreteMotoristaLbl, Style = Estilo.Current[Estilo.TITULO1] }; _Origem = new Label { Text = _frete.EnderecoOrigem, Style = Estilo.Current[Estilo.LABEL_CONTROL] }; _DivisoriaOrigemDestino = new IconImage { IconSize = 20, Margin = new Thickness(10, 0, 10, 0), Icon = "fa-arrow-right" }; _Destino = new Label { Text = _frete.EnderecoDestino, Style = Estilo.Current[Estilo.LABEL_CONTROL] }; _DataSaida = new Label { Text = _frete.DataRetiradaStr, Style = Estilo.Current[Estilo.LABEL_CONTROL] }; _DivisoriaData = new IconImage { IconSize = 20, Margin = new Thickness(10, 0, 10, 0), Icon = "fa-arrow-right" }; _DataChegada = new Label { Text = _frete.DataEntregaStr, Style = Estilo.Current[Estilo.LABEL_CONTROL] }; _Valor = new Label { Text = string.Format("Valor do frete: {0:N}", _frete.Preco), Style = Estilo.Current[Estilo.LABEL_CONTROL] }; _Confirmar = new Button() { Text = "Quero esta carga !", HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, Style = Estilo.Current[Estilo.BTN_SUCESSO] }; if (_frete.MostraP) { selecionado = true; _Confirmar.Text = "Deixar de pedir carga"; } _Confirmar.Clicked += async(sender, e) => { var test = await UserDialogs.Instance.ConfirmAsync((selecionado ? "Você tem certeza que quer deixa a carga ? ": "Você tem certeza que quer esta carga ?"), "Atenção", "Confirmo !", "Voltar"); if (test) { if (!selecionado) { UserDialogs.Instance.ShowLoading("Aceitando..."); //await FreteFactory.create().aceitar(true, _frete.Id, new MotoristaBLL().pegarAtual().Id); await FreteFactory.create().aceitar(new AceiteEnvioInfo { IdFrete = _frete.Id, IdMotorista = new MotoristaBLL().pegarAtual().Id, Aceite = true }); UserDialogs.Instance.HideLoading(); _Confirmar.Text = "Deixar de pedir carga"; selecionado = true; } else { UserDialogs.Instance.ShowLoading("Liberando..."); _frete.Situacao = FreteSituacaoEnum.ProcurandoMotorista; await FreteFactory.create().alterar(_frete); UserDialogs.Instance.HideLoading(); _Confirmar.Text = "Quero esta carga !"; selecionado = false; } } }; }
private void inicializarComponente() { _descricaoLabel = new Label { Style = Estilo.Estilo.Current[Estilo.Estilo.TITULO3], HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, HorizontalTextAlignment = TextAlignment.Center }; _estrela1Icon = criarEstrela((sender, e) => { _Avaliacao = 1; _estrela1Icon.Icon = "fa-star"; _estrela2Icon.Icon = "fa-star-o"; _estrela3Icon.Icon = "fa-star-o"; _estrela4Icon.Icon = "fa-star-o"; _estrela5Icon.Icon = "fa-star-o"; }); _estrela2Icon = criarEstrela((sender, e) => { _Avaliacao = 2; _estrela1Icon.Icon = "fa-star"; _estrela2Icon.Icon = "fa-star"; _estrela3Icon.Icon = "fa-star-o"; _estrela4Icon.Icon = "fa-star-o"; _estrela5Icon.Icon = "fa-star-o"; }); _estrela3Icon = criarEstrela((sender, e) => { _Avaliacao = 3; _estrela1Icon.Icon = "fa-star"; _estrela2Icon.Icon = "fa-star"; _estrela3Icon.Icon = "fa-star"; _estrela4Icon.Icon = "fa-star-o"; _estrela5Icon.Icon = "fa-star-o"; }); _estrela4Icon = criarEstrela((sender, e) => { _Avaliacao = 4; _estrela1Icon.Icon = "fa-star"; _estrela2Icon.Icon = "fa-star"; _estrela3Icon.Icon = "fa-star"; _estrela4Icon.Icon = "fa-star"; _estrela5Icon.Icon = "fa-star-o"; }); _estrela5Icon = criarEstrela((sender, e) => { _Avaliacao = 5; _estrela1Icon.Icon = "fa-star"; _estrela2Icon.Icon = "fa-star"; _estrela3Icon.Icon = "fa-star"; _estrela4Icon.Icon = "fa-star"; _estrela5Icon.Icon = "fa-star"; }); _comentarioEditor = new Editor { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, HeightRequest = 100 }; _confirmarButton = new Button() { Text = "Confirmar", HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, Style = Estilo.Estilo.Current[Estilo.Estilo.BTN_SUCESSO] }; _confirmarButton.Clicked += (sender, e) => { if (_Avaliacao > 0) { AoAvaliar?.Invoke(this, new AvaliacaoInfo(_Avaliacao, _comentarioEditor.Text)); Navigation.PopAsync(); } else { UserDialogs.Instance.AlertAsync("Marque pelomenos uma estrela.", "Aviso", "Entendi"); } }; }
/// <summary> /// Converts this <see cref="Bitmap"/> to an <see cref="Icon"/>. /// </summary> /// <param name="bitmap">The bitmap to convert.</param> public static Icon ToIcon(this Bitmap bitmap) { var bih = new BitmapInfoHeader { biSize = (uint)Marshal.SizeOf(typeof(BitmapInfoHeader)), biWidth = bitmap.Width, biHeight = 2 * bitmap.Height, // include both XOR and AND images biPlanes = 1, biBitCount = 32, biCompression = 0, biSizeImage = 0, biXPelsPerMeter = 0, biYPelsPerMeter = 0, biClrUsed = 0, biClrImportant = 0 }; var xorSize = (((bih.biBitCount * bitmap.Width + 31) & ~31) >> 3) * bitmap.Height; var andLineSize = (((bitmap.Width + 31) & ~31) >> 3); // must be a multiple of 4 bytes var andSize = andLineSize * bitmap.Height; var iconDirEntry = new IconDirEntry { width = (byte)bitmap.Width, height = (byte)bitmap.Height, colorCount = 0, // 32 bbp == 0, for palette size reserved = 0, planes = 0, bitCount = 32, imageOffset = 22, // 22 is the first icon position (for single icon files) bytesInRes = (uint)(bih.biSize + xorSize + andSize) }; var iconImage = new IconImage { iconHeader = bih, iconColors = new uint [0], // no palette iconXOR = new byte [xorSize], iconAND = new byte [andSize] }; var pixel = 0; for (var y = bitmap.Height - 1; y >= 0; y--) { for (var x = 0; x < bitmap.Width; x++) { var color = bitmap.GetPixel(x, y); iconImage.iconXOR [pixel++] = color.B; iconImage.iconXOR [pixel++] = color.G; iconImage.iconXOR [pixel++] = color.R; iconImage.iconXOR [pixel++] = color.A; } } using (var outputStream = new MemoryStream()) using (var streamWriter = new BinaryWriter(outputStream)) { streamWriter.Write((ushort)0); // idReserved must be 0 streamWriter.Write((ushort)1); // idType must be 1 streamWriter.Write((ushort)1); // only one icon SaveIconDirEntry(streamWriter, iconDirEntry); SaveIconImage(streamWriter, iconImage); outputStream.Seek(0, SeekOrigin.Begin); return(new Icon(outputStream)); } }
protected static DialogMockup CreateInstance(IconImage iconImage, double width, double height, Visibility?showButton1, Visibility?showButton2, Visibility?showButton3, Visibility?showMinimizeButton) { return(CreateInstance(iconImage, width, height, null, null, showButton1, showButton2, showButton3, showMinimizeButton, null, null, null)); }
protected virtual void inicializarComponente() { _fotoImage = new Image { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_FOTO] }; _fotoImage.SetBinding(Image.SourceProperty, new Binding("FotoUrl")); _nomeLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.FillAndExpand, Style = Estilo.Current[EstiloProduto.PRODUTO_TITULO] }; _nomeLabel.SetBinding(Label.TextProperty, new Binding("Nome")); _descricaoLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_DESCRICAO] }; _descricaoLabel.SetBinding(Label.TextProperty, new Binding("Descricao")); _moedaValorLabel = new Label { Text = "R$", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_PRECO_MOEDA] }; _moedaValorLabel.SetBinding(Label.TextColorProperty, new Binding("PromocaoCor")); _valorLabel = new Label { VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.End, Style = Estilo.Current[EstiloProduto.PRODUTO_PRECO_VALOR] }; _valorLabel.SetBinding(Label.TextProperty, new Binding("ValorPromocao", stringFormat: "{0:N2}")); _valorLabel.SetBinding(Label.TextColorProperty, new Binding("PromocaoCor")); _volumeLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_VOLUME] }; _volumeLabel.SetBinding(Label.TextProperty, new Binding("VolumeStr")); //_volumeLabel.SetBinding(Label.TextColorProperty, new Binding("PromocaoCor")); _quantidadeLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_QUANTIDADE] }; _quantidadeLabel.SetBinding(Label.TextProperty, new Binding("Quantidade")); _moedaPromocaoLabel = new Label { Text = "R$", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Start, Style = Estilo.Current[EstiloProduto.PRODUTO_PROMOCAO_MOEDA] }; _valorPromocaoLabel = new Label { VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.End, Style = Estilo.Current[EstiloProduto.PRODUTO_PROMOCAO_VALOR] }; _valorPromocaoLabel.SetBinding(Label.TextProperty, new Binding("Valor", stringFormat: "{0:N2}")); var valorLayout = new StackLayout { Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Margin = new Thickness(0, 0, 0, 3), Children = { _moedaPromocaoLabel, _valorPromocaoLabel } }; AbsoluteLayout.SetLayoutBounds(valorLayout, new Rectangle(0, 0, 1, 1)); AbsoluteLayout.SetLayoutFlags(valorLayout, AbsoluteLayoutFlags.All); var linha = new BoxView { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Fill, BackgroundColor = Estilo.Current.DangerColor, HeightRequest = 1, }; AbsoluteLayout.SetLayoutBounds(linha, new Rectangle(0, 0, 1, 1)); AbsoluteLayout.SetLayoutFlags(linha, AbsoluteLayoutFlags.All); _promocaoStack = new AbsoluteLayout { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Children = { valorLayout, linha } }; _promocaoStack.SetBinding(AbsoluteLayout.IsVisibleProperty, new Binding("EmPromocao")); _destaqueIcon = new IconImage { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Icon = "fa-star", Style = Estilo.Current[EstiloProduto.PRODUTO_ICONE] }; _destaqueIcon.SetBinding(Label.IsVisibleProperty, new Binding("Destaque")); _compartilharButton = new IconImage { //VerticalOptions = LayoutOptions.CenterAndExpand, //HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Icon = "fa-share-alt", IconColor = Estilo.Current.PrimaryColor, IconSize = 28, Margin = new Thickness(0, 2) }; var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (sender, e) => { if (!CrossShare.IsSupported) { return; } var produto = (ProdutoInfo)BindingContext; if (produto == null) { return; } CrossShare.Current.Share(new ShareMessage { //Title = produto.Nome, //Text = "R$ " + produto.ValorFinal.ToString("N2"), //Url = "http://smartappcompras.com.br/site/" + produto.Slug Url = produto.Url }); }; _compartilharButton.GestureRecognizers.Add(tapGestureRecognizer); _removerButton = new IconImage { VerticalOptions = LayoutOptions.EndAndExpand, HorizontalOptions = LayoutOptions.Start, Icon = "fa-remove", IconColor = Estilo.Current.DangerColor, IconSize = 28, Margin = new Thickness(0, 2) }; var tapRemover = new TapGestureRecognizer(); tapRemover.Tapped += (sender, e) => { var produto = _quantidadeButton.Produto; if (produto != null) { removerProduto(produto); } }; _removerButton.GestureRecognizers.Add(tapRemover); _quantidadeButton = new QuantidadeVControl { Margin = new Thickness(0, 5, 5, 0), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.End, FontFamily = Estilo.Current.FontDefaultBold, WidthRequest = 40, HeightRequest = 120 }; _quantidadeButton.SetBinding(QuantidadeHControl.QuantidadeProperty, new Binding("QuantidadeCarrinho")); _quantidadeButton.SetBinding(QuantidadeHControl.ProdutoProperty, new Binding(".")); }
protected static DialogMockup CreateInstance( IconImage iconImage, double?width, double?height, Brush background, Brush borderBrush, Visibility?showButton1, Visibility?showButton2, Visibility?showButton3, Visibility?showMinimizeButton, Visibility?showMaximizeButton, Visibility?showFullScreenButton, Visibility?showCloseButton) { DialogMockup dialogMockup = new DialogMockup(); dialogMockup.IconImage = iconImage; if (width.HasValue) { dialogMockup.Width = width.Value; } else { dialogMockup.Width = 300; } if (height.HasValue) { dialogMockup.Height = height.Value; } else { dialogMockup.Height = 100; } if (background != null) { dialogMockup.Background = background; } else { dialogMockup.Background = new SolidColorBrush(BaseBackgroundColor); } if (borderBrush != null) { dialogMockup.BorderBrush = borderBrush; } else { dialogMockup.BorderBrush = new SolidColorBrush(BaseBorderColor); } if (showButton1.HasValue) { dialogMockup.ShowButton1 = showButton1.Value; } else { dialogMockup.ShowButton1 = Visibility.Collapsed; } if (showButton2.HasValue) { dialogMockup.ShowButton2 = showButton2.Value; } else { dialogMockup.ShowButton2 = Visibility.Collapsed; } if (showButton3.HasValue) { dialogMockup.ShowButton3 = showButton3.Value; } else { dialogMockup.ShowButton3 = Visibility.Collapsed; } if (showMinimizeButton.HasValue) { dialogMockup.ShowMinimizeButton = showMinimizeButton.Value; } else { dialogMockup.ShowMinimizeButton = Visibility.Collapsed; } if (showMaximizeButton.HasValue) { dialogMockup.ShowMaximizeButton = showMaximizeButton.Value; } else { dialogMockup.ShowMaximizeButton = Visibility.Collapsed; } if (showCloseButton.HasValue) { dialogMockup.ShowCloseButton = showCloseButton.Value; } else { dialogMockup.ShowCloseButton = Visibility.Visible; } if (showFullScreenButton.HasValue) { dialogMockup.ShowFullScreenButton = showFullScreenButton.Value; } else { dialogMockup.ShowFullScreenButton = Visibility.Collapsed; } dialogMockup.ClearValue(FrameworkElement.StyleProperty); return(dialogMockup); }
Bitmap GetIcon(IconSize imageSize) { // Attempt to extract the icon from the file if (imageSize == IconSize.Medium) { return(Icon.ExtractAssociatedIcon(_imagePath).ToBitmap()); } MultiIcon multicon = new MultiIcon(); try { multicon.Load(_imagePath); } catch (InvalidFileException ex) { if (Log.IsDebugEnabled) { Log.DebugFormat("Failed to get icons from {0}, using default application icon, got exception\n{1}", _imagePath, ex); } return(Icon.ExtractAssociatedIcon(_imagePath).ToBitmap()); } IconImage largeImage = null; IconImage smallImage = null; if (multicon.Count > 0) { SingleIcon icon = multicon[0]; foreach (IconImage iconImage in icon) { // Ignore low quality icons (they look ugly), really big icons (don't need them that big, saves memory) // or really small ones. if (!IsLowQuality(iconImage) && iconImage.Size.Height <= Huge && iconImage.Size.Height >= Small) { if (largeImage == null) { largeImage = iconImage; } if (smallImage == null) { smallImage = iconImage; } if (iconImage.Size.Height > largeImage.Size.Height) { largeImage = iconImage; } if (iconImage.Size.Height < smallImage.Size.Height) { smallImage = iconImage; } } } } if (imageSize == IconSize.Small && smallImage != null) { return(smallImage.Transparent); } if (imageSize == IconSize.Large && largeImage != null) { return(largeImage.Transparent); } return(Icon.ExtractAssociatedIcon(_imagePath).ToBitmap()); }
public override int GetHashCode() { int hashcode = 157; unchecked { if (__isset.channelId) { hashcode = (hashcode * 397) + ChannelId.GetHashCode(); } if (__isset.name) { hashcode = (hashcode * 397) + Name.GetHashCode(); } if (__isset.entryPageUrl) { hashcode = (hashcode * 397) + EntryPageUrl.GetHashCode(); } if (__isset.descriptionText) { hashcode = (hashcode * 397) + DescriptionText.GetHashCode(); } if (__isset.provider) { hashcode = (hashcode * 397) + Provider.GetHashCode(); } if (__isset.publicType) { hashcode = (hashcode * 397) + PublicType.GetHashCode(); } if (__isset.iconImage) { hashcode = (hashcode * 397) + IconImage.GetHashCode(); } if (__isset.permissions) { hashcode = (hashcode * 397) + TCollections.GetHashCode(Permissions); } if (__isset.iconThumbnailImage) { hashcode = (hashcode * 397) + IconThumbnailImage.GetHashCode(); } if (__isset.channelConfigurations) { hashcode = (hashcode * 397) + TCollections.GetHashCode(ChannelConfigurations); } if (__isset.lcsAllApiUsable) { hashcode = (hashcode * 397) + LcsAllApiUsable.GetHashCode(); } if (__isset.allowedPermissions) { hashcode = (hashcode * 397) + TCollections.GetHashCode(AllowedPermissions); } if (__isset.channelDomains) { hashcode = (hashcode * 397) + TCollections.GetHashCode(ChannelDomains); } if (__isset.updatedTimestamp) { hashcode = (hashcode * 397) + UpdatedTimestamp.GetHashCode(); } } return(hashcode); }
/// <summary> /// Saves the current settings. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> async void SaveCurrentSettings(object sender, System.EventArgs e) { OutputDebug("Saving settings (event-based)"); CopySettingsFromController(); if (App.BoardSettings.InFramedMode) { App.BoardSettings.InIconModeAuto = false; resource = App.BoardSettings.InEditMode ? "FastTalkerSkiaSharp.Images.Settings.png" : "FastTalkerSkiaSharp.Images.Speaker.png"; if (App.BoardSettings.IsBottomOriented) { canvas.Icons.Remove(emitterReference); emitterReference = App.ImageBuilderInstance.BuildStaticIconBottom(resource: resource, xPercent: 2f, yPercent: 1.5f, tag: IconRoles.GetRoleInt(IconRoles.Role.Emitter)); canvas.Icons.Add(emitterReference); canvas.Icons.Remove(stripReference); stripReference = App.ImageBuilderInstance.BuildSentenceStripBottom(); canvas.Icons.Add(stripReference); } else { canvas.Icons.Remove(emitterReference); emitterReference = App.ImageBuilderInstance.BuildStaticIcon(resource: resource, xPercent: 2f, yPercent: 1.5f, tag: IconRoles.GetRoleInt(IconRoles.Role.Emitter)); canvas.Icons.Add(emitterReference); canvas.Icons.Remove(stripReference); stripReference = App.ImageBuilderInstance.BuildSentenceStrip(); canvas.Icons.Add(stripReference); } SendReferenceToBack(stripReference); SendReferenceToBack(emitterReference); canvas.InvalidateSurface(); } else { resource = App.BoardSettings.InEditMode ? "FastTalkerSkiaSharp.Images.Settings.png" : "FastTalkerSkiaSharp.Images.Speaker.png"; canvas.Icons.Remove(emitterReference); emitterReference = App.ImageBuilderInstance.BuildStaticIcon(resource: resource, xPercent: 2f, yPercent: 1.5f, tag: IconRoles.GetRoleInt(IconRoles.Role.Emitter)); canvas.Icons.Add(emitterReference); SendReferenceToBack(emitterReference); } if (Xamarin.Forms.Device.RuntimePlatform == Xamarin.Forms.Device.Android) { Xamarin.Forms.DependencyService.Get <Interfaces.InterfaceAdministration>().RequestAdmin(!canvas.Controller.InEditMode); } await App.Database.InsertOrUpdateAsync(App.BoardSettings); if (canvas.Icons[canvas.Icons.IndexOf(emitterReference)].IsPressed) { canvas.Icons[canvas.Icons.IndexOf(emitterReference)].IsPressed = false; canvas.InvalidateSurface(); } ClearIconsInPlay(); }
public override string ToString() { var sb = new StringBuilder("ChannelInfo("); bool __first = true; if (ChannelId != null && __isset.channelId) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("ChannelId: "); ChannelId.ToString(sb); } if (Name != null && __isset.name) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("Name: "); Name.ToString(sb); } if (EntryPageUrl != null && __isset.entryPageUrl) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("EntryPageUrl: "); EntryPageUrl.ToString(sb); } if (DescriptionText != null && __isset.descriptionText) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("DescriptionText: "); DescriptionText.ToString(sb); } if (Provider != null && __isset.provider) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("Provider: "); Provider.ToString(sb); } if (__isset.publicType) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("PublicType: "); PublicType.ToString(sb); } if (IconImage != null && __isset.iconImage) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("IconImage: "); IconImage.ToString(sb); } if (Permissions != null && __isset.permissions) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("Permissions: "); Permissions.ToString(sb); } if (IconThumbnailImage != null && __isset.iconThumbnailImage) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("IconThumbnailImage: "); IconThumbnailImage.ToString(sb); } if (ChannelConfigurations != null && __isset.channelConfigurations) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("ChannelConfigurations: "); ChannelConfigurations.ToString(sb); } if (__isset.lcsAllApiUsable) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("LcsAllApiUsable: "); LcsAllApiUsable.ToString(sb); } if (AllowedPermissions != null && __isset.allowedPermissions) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("AllowedPermissions: "); AllowedPermissions.ToString(sb); } if (ChannelDomains != null && __isset.channelDomains) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("ChannelDomains: "); ChannelDomains.ToString(sb); } if (__isset.updatedTimestamp) { if (!__first) { sb.Append(", "); } __first = false; sb.Append("UpdatedTimestamp: "); UpdatedTimestamp.ToString(sb); } sb.Append(")"); return(sb.ToString()); }
public unsafe MultiIcon Load(Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); hLib = Win32.LoadLibraryEx(tmpFile, IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE); if (hLib == IntPtr.Zero) throw new InvalidFileException(); List<string> iconsIDs; lock (typeof(PEFormat)) { mIconsIDs = new List<string>(); bool bResult = Win32.EnumResourceNames(hLib, (IntPtr) ResourceType.RT_GROUP_ICON, new Win32.EnumResNameProc(EnumResNameProc), IntPtr.Zero); if (bResult == false) { // No Resources in this file } iconsIDs = new List<string>(mIconsIDs); } MultiIcon multiIcon = new MultiIcon(); for(int index=0; index<iconsIDs.Count; index++) { string id = iconsIDs[index]; IntPtr hRsrc = IntPtr.Zero; if (Win32.IS_INTRESOURCE(id)) hRsrc = Win32.FindResource(hLib, int.Parse(id), (IntPtr) ResourceType.RT_GROUP_ICON); else hRsrc = Win32.FindResource(hLib, id, (IntPtr) ResourceType.RT_GROUP_ICON); if (hRsrc == IntPtr.Zero) throw new InvalidFileException(); IntPtr hGlobal = Win32.LoadResource(hLib, hRsrc); if (hGlobal == IntPtr.Zero) throw new InvalidFileException(); MEMICONDIR* pDirectory = (MEMICONDIR*) Win32.LockResource(hGlobal); if (pDirectory->wCount != 0) { MEMICONDIRENTRY* pEntry = &(pDirectory->arEntries); SingleIcon singleIcon = new SingleIcon(id); for(int i=0;i<pDirectory->wCount; i++) { IntPtr hIconInfo = Win32.FindResource(hLib, (IntPtr) pEntry[i].wId, (IntPtr) ResourceType.RT_ICON); if (hIconInfo == IntPtr.Zero) throw new InvalidFileException(); IntPtr hIconRes = Win32.LoadResource(hLib, hIconInfo); if (hIconRes == IntPtr.Zero) throw new InvalidFileException(); IntPtr dibBits = Win32.LockResource(hIconRes); if (dibBits == IntPtr.Zero) throw new InvalidFileException(); buffer = new byte[Win32.SizeofResource(hLib, hIconInfo)]; Marshal.Copy(dibBits, buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(buffer); IconImage iconImage = new IconImage(ms, buffer.Length); singleIcon.Add(iconImage); } multiIcon.Add(singleIcon); } } // If everything went well then lets return the multiIcon. return multiIcon; } catch(Exception) { throw new InvalidFileException(); } finally { if (hLib != null) Win32.FreeLibrary(hLib); if (tmpFile != null) File.Delete(tmpFile); } }
public Bitmap ToBitmap() { Bitmap bmp; if (imageData != null) { // select active icon from the iconDirEntry IconImage ii = imageData [this.id]; MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); try { // write bitmap file header // start with writing signature writer.Write('B'); writer.Write('M'); // write the file size // file size = bitmapfileheader + bitmapinfo + // colorpalette + image bits // sizeof bitmapfileheader = 14 bytes // sizeof bitmapinfo = 40 bytes uint offSet = (uint)(14 + 40 + ii.iconColors.Length * 4); uint fileSize = (uint)(offSet + ii.iconXOR.Length); writer.Write(fileSize); // write reserved words ushort reserved12 = 0; writer.Write(reserved12); writer.Write(reserved12); // write offset writer.Write(offSet); // write bitmapfile header BitmapInfoHeader bih = ii.iconHeader; writer.Write(bih.biSize); writer.Write(bih.biWidth); writer.Write(bih.biHeight / 2); writer.Write(bih.biPlanes); writer.Write(bih.biBitCount); writer.Write(bih.biCompression); writer.Write(bih.biSizeImage); writer.Write(bih.biXPelsPerMeter); writer.Write(bih.biYPelsPerMeter); writer.Write(bih.biClrUsed); writer.Write(bih.biClrImportant); // write color table int colCount = ii.iconColors.Length; for (int j = 0; j < colCount; j++) { writer.Write(ii.iconColors [j]); } // write image bits writer.Write(ii.iconXOR); writer.Flush(); stream.Position = 0; // create bitmap from stream and return if (colCount > 0) { Bitmap new_bmp; new_bmp = new Bitmap(stream); bmp = new Bitmap(new_bmp, bih.biWidth, bih.biHeight / 2); new_bmp.Dispose(); } else { bmp = new Bitmap(stream); } // This hack is so ugly, it's embarassing. // But icons are small, so it should be ok for now for (int y = 0; y < bih.biHeight / 2; y++) { for (int x = 0; x < bih.biWidth / 8; x++) { for (int bit = 7; bit >= 0; bit--) { if (((ii.iconAND[y * bih.biWidth / 8 + x] >> bit) & 1) != 0) { bmp.SetPixel(x * 8 + 7 - bit, bih.biHeight / 2 - y - 1, Color.Transparent); } } } } } catch (Exception e) { throw e; } finally { writer.Close(); // closes the underlying stream as well } } else { bmp = new Bitmap(32, 32); } return(bmp); }
private void SaveBitmapAsIcon (BinaryWriter writer) { writer.Write ((ushort)0); // idReserved must be 0 writer.Write ((ushort)1); // idType must be 1 writer.Write ((ushort)1); // only one icon // when transformed into a bitmap only a single image exists IconDirEntry ide = new IconDirEntry (); ide.width = (byte) bitmap.Width; ide.height = (byte) bitmap.Height; ide.colorCount = 0; // 32 bbp == 0, for palette size ide.reserved = 0; // always 0 ide.planes = 0; ide.bitCount = 32; ide.imageOffset = 22; // 22 is the first icon position (for single icon files) BitmapInfoHeader bih = new BitmapInfoHeader (); bih.biSize = (uint) Marshal.SizeOf (typeof (BitmapInfoHeader)); bih.biWidth = bitmap.Width; bih.biHeight = 2 * bitmap.Height; // include both XOR and AND images bih.biPlanes = 1; bih.biBitCount = 32; bih.biCompression = 0; bih.biSizeImage = 0; bih.biXPelsPerMeter = 0; bih.biYPelsPerMeter = 0; bih.biClrUsed = 0; bih.biClrImportant = 0; IconImage ii = new IconImage (); ii.iconHeader = bih; ii.iconColors = new uint [0]; // no palette int xor_size = (((bih.biBitCount * bitmap.Width + 31) & ~31) >> 3) * bitmap.Height; ii.iconXOR = new byte [xor_size]; int p = 0; for (int y = bitmap.Height - 1; y >=0; y--) { for (int x = 0; x < bitmap.Width; x++) { Color c = bitmap.GetPixel (x, y); ii.iconXOR [p++] = c.B; ii.iconXOR [p++] = c.G; ii.iconXOR [p++] = c.R; ii.iconXOR [p++] = c.A; } } int and_line_size = (((Width + 31) & ~31) >> 3); // must be a multiple of 4 bytes int and_size = and_line_size * bitmap.Height; ii.iconAND = new byte [and_size]; ide.bytesInRes = (uint) (bih.biSize + xor_size + and_size); SaveIconDirEntry (writer, ide, UInt32.MaxValue); SaveIconImage (writer, ii); }
private void InitFromStreamWithSize(Stream stream, int width, int height) { //read the icon header if (stream == null || stream.Length == 0) { throw new System.ArgumentException("The argument 'stream' must be a picture that can be used as a Icon", "stream"); } BinaryReader reader = new BinaryReader(stream); //iconDir = new IconDir (); iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 { throw new System.ArgumentException("Invalid Argument", "stream"); } iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 { throw new System.ArgumentException("Invalid Argument", "stream"); } ushort dirEntryCount = reader.ReadUInt16(); iconDir.idCount = dirEntryCount; iconDir.idEntries = new IconDirEntry [dirEntryCount]; imageData = new IconImage [dirEntryCount]; bool sizeObtained = false; //now read in the IconDirEntry structures for (int i = 0; i < dirEntryCount; i++) { IconDirEntry ide; ide.width = reader.ReadByte(); ide.height = reader.ReadByte(); ide.colorCount = reader.ReadByte(); ide.reserved = reader.ReadByte(); ide.planes = reader.ReadUInt16(); ide.bitCount = reader.ReadUInt16(); ide.bytesInRes = reader.ReadUInt32(); ide.imageOffset = reader.ReadUInt32(); iconDir.idEntries [i] = ide; //is this is the best fit?? if (!sizeObtained) { if (ide.height == height && ide.width == width) { this.id = (ushort)i; sizeObtained = true; this.iconSize.Height = ide.height; this.iconSize.Width = ide.width; } } } //if we havent found the best match, return the one with the //largest size. Is this approach correct?? if (!sizeObtained) { uint largestSize = 0; for (int j = 0; j < dirEntryCount; j++) { if (iconDir.idEntries [j].bytesInRes >= largestSize) { largestSize = iconDir.idEntries [j].bytesInRes; this.id = (ushort)j; this.iconSize.Height = iconDir.idEntries [j].height; this.iconSize.Width = iconDir.idEntries [j].width; } } } //now read in the icon data for (int j = 0; j < dirEntryCount; j++) { IconImage iidata = new IconImage(); BitmapInfoHeader bih = new BitmapInfoHeader(); stream.Seek(iconDir.idEntries [j].imageOffset, SeekOrigin.Begin); byte [] buffer = new byte [iconDir.idEntries [j].bytesInRes]; stream.Read(buffer, 0, buffer.Length); BinaryReader bihReader = new BinaryReader(new MemoryStream(buffer)); bih.biSize = bihReader.ReadUInt32(); bih.biWidth = bihReader.ReadInt32(); bih.biHeight = bihReader.ReadInt32(); bih.biPlanes = bihReader.ReadUInt16(); bih.biBitCount = bihReader.ReadUInt16(); bih.biCompression = bihReader.ReadUInt32(); bih.biSizeImage = bihReader.ReadUInt32(); bih.biXPelsPerMeter = bihReader.ReadInt32(); bih.biYPelsPerMeter = bihReader.ReadInt32(); bih.biClrUsed = bihReader.ReadUInt32(); bih.biClrImportant = bihReader.ReadUInt32(); iidata.iconHeader = bih; //Read the number of colors used and corresponding memory occupied by //color table. Fill this memory chunk into rgbquad[] int numColors; switch (bih.biBitCount) { case 1: numColors = 2; break; case 4: numColors = 16; break; case 8: numColors = 256; break; default: numColors = 0; break; } iidata.iconColors = new uint [numColors]; for (int i = 0; i < numColors; i++) { iidata.iconColors [i] = bihReader.ReadUInt32(); } //XOR mask is immediately after ColorTable and its size is //icon height* no. of bytes per line //icon height is half of BITMAPINFOHEADER.biHeight, since it contains //both XOR as well as AND mask bytes int iconHeight = bih.biHeight / 2; //bytes per line should should be uint aligned int numBytesPerLine = ((((bih.biWidth * bih.biPlanes * bih.biBitCount) + 31) >> 5) << 2); //Determine the XOR array Size int xorSize = numBytesPerLine * iconHeight; iidata.iconXOR = new byte [xorSize]; for (int i = 0; i < xorSize; i++) { iidata.iconXOR[i] = bihReader.ReadByte(); } //Determine the AND array size //For this i subtract the current position from the length. //ugly hack... int andSize = (int)(bihReader.BaseStream.Length - bihReader.BaseStream.Position); iidata.iconAND = new byte [andSize]; for (int i = 0; i < andSize; i++) { iidata.iconAND[i] = bihReader.ReadByte(); } imageData [j] = iidata; bihReader.Close(); } reader.Close(); }
void ReleaseDesignerOutlets() { if (CurrentLocationButton != null) { CurrentLocationButton.Dispose(); CurrentLocationButton = null; } if (Humid1Label != null) { Humid1Label.Dispose(); Humid1Label = null; } if (IconImage != null) { IconImage.Dispose(); IconImage = null; } if (SettingsButton != null) { SettingsButton.Dispose(); SettingsButton = null; } if (Speed1Label != null) { Speed1Label.Dispose(); Speed1Label = null; } if (StartGpsButton != null) { StartGpsButton.Dispose(); StartGpsButton = null; } if (SummaryLabel != null) { SummaryLabel.Dispose(); SummaryLabel = null; } if (Temp1Label != null) { Temp1Label.Dispose(); Temp1Label = null; } if (TimeLabel != null) { TimeLabel.Dispose(); TimeLabel = null; } if (TimezoneInfoLabel != null) { TimezoneInfoLabel.Dispose(); TimezoneInfoLabel = null; } if (WeatherRootView != null) { WeatherRootView.Dispose(); WeatherRootView = null; } if (WeekDayLabel != null) { WeekDayLabel.Dispose(); WeekDayLabel = null; } if (WeekTableView != null) { WeekTableView.Dispose(); WeekTableView = null; } }
public unsafe void Save(MultiIcon multiIcon, Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; MemoryStream ms; bool bResult; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); // Read EmptyDll.dll into byte array Assembly assembly = Assembly.GetExecutingAssembly(); Stream emptyDllStream = assembly.GetManifestResourceStream("EmptyDll.dll"); byte[] buffer = new byte[emptyDllStream.Length]; emptyDllStream.Read(buffer, 0, (int)emptyDllStream.Length); stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); // Begin the injection process IntPtr updPtr = Win32.BeginUpdateResource(tmpFile, false); if (updPtr == IntPtr.Zero) { throw new InvalidFileException(); } ushort iconIndex = 1; foreach (SingleIcon singleIcon in multiIcon) { // Lets scan all groups GRPICONDIR grpIconDir = GRPICONDIR.Initalizated; grpIconDir.idCount = (ushort)singleIcon.Count; grpIconDir.idEntries = new GRPICONDIRENTRY[grpIconDir.idCount]; for (int i = 0; i < singleIcon.Count; i++) { // Inside every Icon let update every image format IconImage iconImage = singleIcon[i]; grpIconDir.idEntries[i] = iconImage.GRPICONDIRENTRY; grpIconDir.idEntries[i].nID = iconIndex; // Buffer creation with the same size of the icon to optimize write call ms = new MemoryStream((int)grpIconDir.idEntries[i].dwBytesInRes); iconImage.Write(ms); buffer = ms.GetBuffer(); // Update resource but it doesn't write to disk yet bResult = Win32.UpdateResource(updPtr, (int)ResourceType.RT_ICON, iconIndex, 0, buffer, (uint)ms.Length); iconIndex++; // For some reason Windows will fail if there are many calls to update resource and no call to endUpdateResource // It is like there some internal buffer that gets full, after that all calls fail. // This workaround will save the changes every 70 icons, for big files this slow the saving process significantly // but I didn't find a way to make EndUpdateResource works without save frequently if ((iconIndex % 70) == 0) { bResult = Win32.EndUpdateResource(updPtr, false); updPtr = Win32.BeginUpdateResource(tmpFile, false); if (updPtr == IntPtr.Zero) { throw new InvalidFileException(); } } } // Buffer creation with the same size of the group to optimize write call ms = new MemoryStream(grpIconDir.GroupDirSize); grpIconDir.Write(ms); buffer = ms.GetBuffer(); int id; if (int.TryParse(singleIcon.Name, out id)) { // Write id as an integer bResult = Win32.UpdateResource(updPtr, (int)ResourceType.RT_GROUP_ICON, (IntPtr)id, 0, buffer, (uint)ms.Length); } else { // Write id as string IntPtr pName = Marshal.StringToHGlobalAnsi(singleIcon.Name.ToUpper()); bResult = Win32.UpdateResource(updPtr, (int)ResourceType.RT_GROUP_ICON, pName, 0, buffer, (uint)ms.Length); Marshal.FreeHGlobal(pName); } } // Last call to update the file with the rest not that was not write before bResult = Win32.EndUpdateResource(updPtr, false); // Because Windows Resource functions requiere a filepath, and we need to return an string then lets open // the temporary file and dump it to the stream received as parameter. fs = new FileStream(tmpFile, FileMode.Open, FileAccess.Read); buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, buffer.Length); fs.Close(); } catch (Exception) { throw new InvalidFileException(); } finally { if (hLib != null) { Win32.FreeLibrary(hLib); } if (tmpFile != null) { File.Delete(tmpFile); } } }
private void InitFromStreamWithSize(Stream stream, int width, int height) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (stream.Length == 0) { throw new System.ArgumentException("The argument 'stream' must be a picture that can be used as a Icon", nameof(stream)); } //read the icon header BinaryReader reader = new BinaryReader(stream); //iconDir = new IconDir (); iconDir.idReserved = reader.ReadUInt16(); if (iconDir.idReserved != 0) //must be 0 { throw new System.ArgumentException("Invalid Argument", nameof(stream)); } iconDir.idType = reader.ReadUInt16(); if (iconDir.idType != 1) //must be 1 { throw new System.ArgumentException("Invalid Argument", nameof(stream)); } ushort dirEntryCount = reader.ReadUInt16(); imageData = new ImageData[dirEntryCount]; iconDir.idCount = dirEntryCount; iconDir.idEntries = new IconDirEntry[dirEntryCount]; bool sizeObtained = false; // now read in the IconDirEntry structures for (int i = 0; i < dirEntryCount; i++) { IconDirEntry ide; ide.width = reader.ReadByte(); ide.height = reader.ReadByte(); ide.colorCount = reader.ReadByte(); ide.reserved = reader.ReadByte(); ide.planes = reader.ReadUInt16(); ide.bitCount = reader.ReadUInt16(); ide.bytesInRes = reader.ReadUInt32(); ide.imageOffset = reader.ReadUInt32(); // Vista 256x256 icons points directly to a PNG bitmap // 256x256 icons are decoded as 0x0 (width and height are encoded as BYTE) // and we ignore them just like MS does (at least up to fx 2.0) // Added: storing data so it can be saved back if ((ide.width == 0) && (ide.height == 0)) { ide.ignore = true; } else { ide.ignore = false; } iconDir.idEntries[i] = ide; //is this is the best fit?? if (!sizeObtained) { if (((ide.height == height) || (ide.width == width)) && !ide.ignore) { this.id = (ushort)i; sizeObtained = true; this.iconSize.Height = ide.height; this.iconSize.Width = ide.width; } } } // throw error if no valid entries found int valid = 0; for (int i = 0; i < dirEntryCount; i++) { if (!(iconDir.idEntries[i].ignore)) { valid++; } } if (valid == 0) { throw new Win32Exception(0, "No valid icon entry were found."); } // if we havent found the best match, return the one with the // largest size. Is this approach correct?? if (!sizeObtained) { uint largestSize = 0; for (int j = 0; j < dirEntryCount; j++) { if (iconDir.idEntries[j].bytesInRes >= largestSize && !iconDir.idEntries[j].ignore) { largestSize = iconDir.idEntries[j].bytesInRes; this.id = (ushort)j; this.iconSize.Height = iconDir.idEntries[j].height; this.iconSize.Width = iconDir.idEntries[j].width; } } } //now read in the icon data for (int j = 0; j < dirEntryCount; j++) { // process ignored into IconDump if (iconDir.idEntries[j].ignore) { IconDump id = new IconDump(); stream.Seek(iconDir.idEntries[j].imageOffset, SeekOrigin.Begin); id.data = new byte[iconDir.idEntries[j].bytesInRes]; stream.Read(id.data, 0, id.data.Length); imageData[j] = id; continue; } // standard image IconImage iidata = new IconImage(); BitmapInfoHeader bih = new BitmapInfoHeader(); stream.Seek(iconDir.idEntries[j].imageOffset, SeekOrigin.Begin); byte[] buffer = new byte[iconDir.idEntries[j].bytesInRes]; stream.Read(buffer, 0, buffer.Length); BinaryReader bihReader = new BinaryReader(new MemoryStream(buffer)); bih.biSize = bihReader.ReadUInt32(); bih.biWidth = bihReader.ReadInt32(); bih.biHeight = bihReader.ReadInt32(); bih.biPlanes = bihReader.ReadUInt16(); bih.biBitCount = bihReader.ReadUInt16(); bih.biCompression = bihReader.ReadUInt32(); bih.biSizeImage = bihReader.ReadUInt32(); bih.biXPelsPerMeter = bihReader.ReadInt32(); bih.biYPelsPerMeter = bihReader.ReadInt32(); bih.biClrUsed = bihReader.ReadUInt32(); bih.biClrImportant = bihReader.ReadUInt32(); iidata.iconHeader = bih; //Read the number of colors used and corresponding memory occupied by //color table. Fill this memory chunk into rgbquad[] int numColors; switch (bih.biBitCount) { case 1: numColors = 2; break; case 4: numColors = 16; break; case 8: numColors = 256; break; default: numColors = 0; break; } iidata.iconColors = new uint[numColors]; for (int i = 0; i < numColors; i++) { iidata.iconColors[i] = bihReader.ReadUInt32(); } //XOR mask is immediately after ColorTable and its size is //icon height* no. of bytes per line //icon height is half of BITMAPINFOHEADER.biHeight, since it contains //both XOR as well as AND mask bytes int iconHeight = bih.biHeight / 2; //bytes per line should should be uint aligned int numBytesPerLine = ((((bih.biWidth * bih.biPlanes * bih.biBitCount) + 31) >> 5) << 2); //Determine the XOR array Size int xorSize = numBytesPerLine * iconHeight; iidata.iconXOR = new byte[xorSize]; int nread = bihReader.Read(iidata.iconXOR, 0, xorSize); if (nread != xorSize) { string msg = string.Format("{0} data length expected {1}, read {2}", "XOR", xorSize, nread); throw new ArgumentException(msg, nameof(stream)); } //Determine the AND array size numBytesPerLine = (int)((((bih.biWidth) + 31) & ~31) >> 3); int andSize = numBytesPerLine * iconHeight; iidata.iconAND = new byte[andSize]; nread = bihReader.Read(iidata.iconAND, 0, andSize); if (nread != andSize) { string msg = string.Format("{0} data length expected {1}, read {2}", "AND", andSize, nread); throw new ArgumentException(msg, nameof(stream)); } imageData[j] = iidata; bihReader.Dispose(); } reader.Dispose(); }
public unsafe MultiIcon Load(Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); hLib = Win32.LoadLibraryEx(tmpFile, IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE); if (hLib == IntPtr.Zero) { throw new InvalidFileException(); } List <string> iconsIDs; lock (typeof(PEFormat)) { mIconsIDs = new List <string>(); bool bResult = Win32.EnumResourceNames(hLib, (IntPtr)ResourceType.RT_GROUP_ICON, new Win32.EnumResNameProc(EnumResNameProc), IntPtr.Zero); if (bResult == false) { // No Resources in this file } iconsIDs = new List <string>(mIconsIDs); } MultiIcon multiIcon = new MultiIcon(); for (int index = 0; index < iconsIDs.Count; index++) { string id = iconsIDs[index]; IntPtr hRsrc = IntPtr.Zero; if (Win32.IS_INTRESOURCE(id)) { hRsrc = Win32.FindResource(hLib, int.Parse(id), (IntPtr)ResourceType.RT_GROUP_ICON); } else { hRsrc = Win32.FindResource(hLib, id, (IntPtr)ResourceType.RT_GROUP_ICON); } if (hRsrc == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr hGlobal = Win32.LoadResource(hLib, hRsrc); if (hGlobal == IntPtr.Zero) { throw new InvalidFileException(); } MEMICONDIR *pDirectory = (MEMICONDIR *)Win32.LockResource(hGlobal); if (pDirectory->wCount != 0) { MEMICONDIRENTRY *pEntry = &(pDirectory->arEntries); SingleIcon singleIcon = new SingleIcon(id); for (int i = 0; i < pDirectory->wCount; i++) { IntPtr hIconInfo = Win32.FindResource(hLib, (IntPtr)pEntry[i].wId, (IntPtr)ResourceType.RT_ICON); if (hIconInfo == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr hIconRes = Win32.LoadResource(hLib, hIconInfo); if (hIconRes == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr dibBits = Win32.LockResource(hIconRes); if (dibBits == IntPtr.Zero) { throw new InvalidFileException(); } buffer = new byte[Win32.SizeofResource(hLib, hIconInfo)]; Marshal.Copy(dibBits, buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(buffer); IconImage iconImage = new IconImage(ms, buffer.Length); singleIcon.Add(iconImage); } multiIcon.Add(singleIcon); } } // If everything went well then lets return the multiIcon. return(multiIcon); } catch (Exception) { throw new InvalidFileException(); } finally { if (hLib != null) { Win32.FreeLibrary(hLib); } if (tmpFile != null) { File.Delete(tmpFile); } } }
private void inicializarComponente() { _fotoImage = new Image { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.CenterAndExpand, WidthRequest = 400, HeightRequest = 300, Aspect = Aspect.AspectFit }; _fotoImage.SetBinding(Image.SourceProperty, new Binding("FotoUrl")); _descricaoLabel = new Label { FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, TextColor = Color.FromHex("#777777") }; _descricaoLabel.SetBinding(Label.TextProperty, new Binding("Descricao")); _categoriaLabel = new Label { FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, TextColor = Color.FromHex("#777777") }; _categoriaLabel.SetBinding(Label.TextProperty, new Binding("Categoria.Nome")); _codigoLabel = new Label { FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, TextColor = Color.FromHex("#777777") }; _codigoLabel.SetBinding(Label.TextProperty, new Binding("Codigo")); _moedaValorLabel = new Label { Text = "R$", FontSize = 11, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Start }; _moedaValorLabel.SetBinding(Label.TextColorProperty, new Binding("PromocaoCor")); _valorFinalLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.End, FontFamily = Estilo.Current.FontDefaultBold, FontAttributes = FontAttributes.Bold, FontSize = 24 }; _valorFinalLabel.SetBinding(Label.TextProperty, new Binding("ValorFinal", stringFormat: "{0:N2}")); _valorFinalLabel.SetBinding(Label.TextColorProperty, new Binding("PromocaoCor")); _volumeLabel = new Label { FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, TextColor = Color.FromHex("#777777") }; _volumeLabel.SetBinding(Label.TextProperty, new Binding("VolumeStr")); _quantidadeLabel = new Label { FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, TextColor = Color.FromHex("#777777") }; _quantidadeLabel.SetBinding(Label.TextProperty, new Binding("Quantidade")); _moedaPromocaoLabel = new Label { Text = "R$", FontSize = 11, //TextColor = Estilo.Current.D, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Start }; _valorPromocaoLabel = new Label { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.End, FontFamily = Estilo.Current.FontDefaultBold, //TextColor = Estilo.Current.DangerColor, FontAttributes = FontAttributes.Bold, FontSize = 24 }; _valorPromocaoLabel.SetBinding(Label.TextProperty, new Binding("Valor", stringFormat: "{0:N2}")); var valorLayout = new StackLayout { Orientation = StackOrientation.Horizontal, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Margin = new Thickness(0, 0, 0, 3), Children = { _moedaPromocaoLabel, _valorPromocaoLabel } }; AbsoluteLayout.SetLayoutBounds(valorLayout, new Rectangle(0, 0, 1, 1)); AbsoluteLayout.SetLayoutFlags(valorLayout, AbsoluteLayoutFlags.All); var linha = new BoxView { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Fill, BackgroundColor = Estilo.Current.DangerColor, HeightRequest = 1, }; AbsoluteLayout.SetLayoutBounds(linha, new Rectangle(0, 0, 1, 1)); AbsoluteLayout.SetLayoutFlags(linha, AbsoluteLayoutFlags.All); _promocaoStack = new AbsoluteLayout { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Children = { valorLayout, linha } }; _promocaoStack.SetBinding(AbsoluteLayout.IsVisibleProperty, new Binding("EmPromocao")); _quantidadeButton = new QuantidadeVControl { Margin = new Thickness(0, 5, 5, 0), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.End, FontFamily = Estilo.Current.FontDefaultBold, HeightRequest = 120 }; _quantidadeButton.SetBinding(QuantidadeHControl.QuantidadeProperty, new Binding("QuantidadeCarrinho")); _quantidadeButton.SetBinding(QuantidadeHControl.ProdutoProperty, new Binding(".")); _destaqueIcon = new IconImage { VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start, Icon = "fa-star", IconColor = Color.FromHex("#ffc500"), IconSize = 24 }; _destaqueIcon.SetBinding(Label.IsVisibleProperty, new Binding("Destaque")); _totalView = new TotalCarrinhoView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.End, ExibeQuantidade = true, ExibeTotal = true }; _empresaLabel = new Label { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Start, HorizontalTextAlignment = TextAlignment.Center, FontAttributes = FontAttributes.Bold, Margin = new Thickness(0, 0, 0, 3), Text = "Smart Tecnologia ®" }; }
/// <summary> /// Builds user interface icons /// </summary> /// <returns>The named icon.</returns> /// <param name="resource">Resource.</param> /// <param name="text">Text.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="tagCode">Tag code.</param> /// <param name="alignRight">If set to <c>true</c> align right.</param> /// <param name="alignBottom">If set to <c>true</c> align bottom.</param> /// <param name="opaqueBackground">If set to <c>true</c> opaque background.</param> public IconImage BuildNamedIcon(string resource, string text, float x, float y, int tagCode, bool alignRight = false, bool alignBottom = false, bool opaqueBackground = false) { IconImage image = null; SKSize loadedSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, 1f, 1f); using (System.IO.Stream stream = App.MainAssembly.GetManifestResourceStream(resource)) { SKBitmap tempBitmapPre = SKBitmap.Decode(stream); SKBitmap tempBitmap = tempBitmapPre.Resize(new SKImageInfo((int)loadedSize.Width, (int)loadedSize.Width), SKBitmapResizeMethod.Lanczos3); //SkiaSharp.SKBitmap tempBitmap = SkiaSharp.SKBitmap.Decode(stream); SKBitmap returnBitmap = new SKBitmap((int)System.Math.Round(tempBitmap.Width * 1.5), (int)System.Math.Round(tempBitmap.Height * 1.5), tempBitmap.ColorType, tempBitmap.AlphaType); using (SKCanvas canvas2 = new SKCanvas(returnBitmap)) { if (opaqueBackground) { canvas2.Clear(SKColors.White); } else { canvas2.Clear(SKColors.Transparent); } canvas2.DrawBitmap(tempBitmap, SKRect.Create(System.Convert.ToInt16(tempBitmap.Width * 0.25), System.Convert.ToInt16(tempBitmap.Height * 0.1), tempBitmap.Width, tempBitmap.Height)); using (SKPaint paint = new SKPaint()) { paint.TextSize = Constants.DeviceLayout.TextSizeDefault * App.DisplayScaleFactor; paint.IsAntialias = true; paint.Color = SKColors.Black; paint.TextAlign = SKTextAlign.Center; canvas2.DrawText(text, (System.Convert.ToSingle(tempBitmap.Width) * 1.5f) / 2f, (System.Convert.ToSingle(tempBitmap.Height) * 1.35f), paint); } canvas2.Flush(); SKSize finalSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, Constants.DeviceLayout.InterfaceDimensionDefault, Constants.DeviceLayout.InterfaceDimensionDefault); SKPoint settingsPoint; if ((int)x == -1 || (int)y == -1) { settingsPoint = Constants.DeviceLayout.GetCenterPoint(canvasReference.CanvasSize); } else { settingsPoint = new SKPoint(x, y); } if (alignRight) { settingsPoint.X -= finalSize.Width; } if (alignBottom) { settingsPoint.Y -= finalSize.Height; } image = new IconImage(returnBitmap) { Tag = tagCode, Text = text, BorderColor = SKColors.Black, LocalImage = true, ImageInformation = resource, IsInsertableIntoFolder = false, StoredFolderTag = "", BorderWidth = 2f, Bounds = SKRect.Create(settingsPoint, finalSize) }; return(image); } } }