public MainWindow() { initializing = true; mySettings = new AppSettings(SettingsFileName); InitializeComponent(); //Load the input image. if (File.Exists(mySettings.InputFilePath)) { SetInputImage(mySettings.InputFilePath); } else if (Img_Input.Source is BitmapImage) { inputBmp = (BitmapImage)Img_Input.Source; } RenderOptions.SetBitmapScalingMode(Img_Input, BitmapScalingMode.NearestNeighbor); //Load previously-used settings. Textbox_TileWidth.Text = mySettings.TileSizeX.ToString(); Textbox_TileHeight.Text = mySettings.TileSizeY.ToString(); Textbox_Seed.Text = mySettings.Seed; Check_PeriodicInputX.IsChecked = mySettings.PeriodicInputX; Check_PeriodicInputY.IsChecked = mySettings.PeriodicInputY; Check_MirrorInput.IsChecked = mySettings.MirrorInput; Check_RotateInput.IsChecked = mySettings.RotateInput; //Disable the "Generate" button until an input image is chosen. if (Img_Input.Source == null) { Button_GenerateImg.IsEnabled = false; } initializing = false; }
public override void Execute(TabItem contextViewModel, object parameter) { if (parameter == null || !contextViewModel.HasImage) { return; } switch (parameter) { case "Open": { Helper.OpenWindow <AdonisWindow>(contextViewModel.Header + " (Image)", () => { var popout = new ImagePopout { Title = contextViewModel.Header + " (Image)", Width = contextViewModel.Image.Width, Height = contextViewModel.Image.Height, WindowState = contextViewModel.Image.Height > 1000 ? WindowState.Maximized : WindowState.Normal, ImageCtrl = { Source = contextViewModel.Image } }; RenderOptions.SetBitmapScalingMode(popout.ImageCtrl, contextViewModel.ImageRender); popout.Show(); }); break; } case "Copy": Clipboard.SetImage(contextViewModel.Image); break; case "Save": contextViewModel.SaveImage(false); break; } }
static void Main(string[] args) { i = new Image(); RenderOptions.SetBitmapScalingMode(i, BitmapScalingMode.NearestNeighbor); RenderOptions.SetEdgeMode(i, EdgeMode.Aliased); w = new Window(); w.Content = i; w.Show(); writeableBitmap = new WriteableBitmap( ( int )w.ActualWidth, ( int )w.ActualHeight, 96, 96, PixelFormats.Bgr32, null); i.Source = writeableBitmap; i.Stretch = Stretch.None; i.HorizontalAlignment = HorizontalAlignment.Left; i.VerticalAlignment = VerticalAlignment.Top; i.MouseMove += new MouseEventHandler(i_MouseMove); i.MouseLeftButtonDown += new MouseButtonEventHandler(i_MouseLeftButtonDown); i.MouseRightButtonDown += new MouseButtonEventHandler(i_MouseRightButtonDown); w.MouseWheel += new MouseWheelEventHandler(w_MouseWheel); Application app = new Application(); app.Run(); }
public static BitmapFrame Resize(this BitmapSource photo, int width, int height, BitmapScalingMode scalingMode) { var group = new DrawingGroup(); RenderOptions.SetBitmapScalingMode( group, scalingMode); group.Children.Add( new ImageDrawing(photo, new Rect(0, 0, width, height))); var targetVisual = new DrawingVisual(); var targetContext = targetVisual.RenderOpen(); targetContext.DrawDrawing(group); var target = new RenderTargetBitmap( width, height, 96, 96, PixelFormats.Default); targetContext.Close(); target.Render(targetVisual); var targetFrame = BitmapFrame.Create(target); return(targetFrame); }
private void DrawProperties() { _propertiesBitmap = new WriteableBitmap(Screen.PixelWidth, Screen.PixelHeight, 96, 96, PixelFormats.Pbgra32, null); RenderOptions.SetBitmapScalingMode(_propertiesBitmap, BitmapScalingMode.NearestNeighbor); var size = Screen.Tileset.TileSize; for (int y = 0; y < Screen.Height; y++) { for (int x = 0; x < Screen.Width; x++) { var tile = Screen.TileAt(x, y); if (tile.Properties.Sinking != 0 || tile.Properties.PushX != 0 || tile.Properties.PushY != 0) { _propertiesBitmap.FillRectangle(x * size, y * size, (x + 1) * size, (y + 1) * size, Colors.Purple); } else if (tile.Properties.Blocking) { _propertiesBitmap.FillRectangle(x * size, y * size, (x + 1) * size, (y + 1) * size, Colors.Green); } else if (tile.Properties.Lethal) { _propertiesBitmap.FillRectangle(x * size, y * size, (x + 1) * size, (y + 1) * size, Colors.Red); } else if (tile.Properties.Climbable) { _propertiesBitmap.FillRectangle(x * size, y * size, (x + 1) * size, (y + 1) * size, Colors.Yellow); } else if (tile.Properties.GravityMult < 1) { _propertiesBitmap.FillRectangle(x * size, y * size, (x + 1) * size, (y + 1) * size, Colors.LightBlue); } } } }
/// <summary> /// Creates a new photo and adds it as a touch managed object to the MTElementDictionary withing the framework. /// Randomly positions and rotates the photo within the screen area. /// </summary> /// <param name="filePath">Full path to the image.</param> void AddPhoto(string filePath) { BitmapImage bi = new BitmapImage(new Uri(filePath)); Photo p = new Photo(); System.Windows.Controls.Image i = p.SetPicture(filePath); RenderOptions.SetBitmapScalingMode(i, BitmapScalingMode.HighQuality); ElementProperties prop = new ElementProperties(); prop.ElementSupport.AddSupportForAll(); MTContainer cont = new MTSmoothContainer(p, canvas1, prop); framework.RegisterElement(cont); canvas1.Children.Add(p); cont.MaxX = (int)(this.screen_width); cont.MaxY = (int)(this.screen_height); cont.MinX = (int)(this.screen_width / 10); cont.MinY = (int)(this.screen_height / 10); }
void SetInitImg(ImageBrush[] cornerImg, Canvas oriCanvas, Canvas Pro, Canvas[] cornerCanv) { List <Rectangle> rectList = new List <Rectangle>(); /*Canvas Setting*/ while (oriCanvas.Children.Count > 0) { oriCanvas.Children.Clear(); } double[] canvXYLen = Core.MapImg2Canv(new double[2] { Core.LTRBPixelNumberH, Core.LTRBPixelNumberW }); Core.SetCornerRect(oriCanvas, canvXYLen[0], canvXYLen[1]); RenderOptions.SetBitmapScalingMode(Pro, BitmapScalingMode.NearestNeighbor); for (int i = 0; i < 4; i++) { RenderOptions.SetBitmapScalingMode(cornerCanv[i], BitmapScalingMode.HighQuality); var temp = CornerImgCrops[i](Core.OriginImg); cornerImg[i].ImageSource = BitmapSrcConvert.ToBitmapSource(CornerImgCrops[i](Core.OriginImg)); cornerCanv[i].MouseLeftButtonUp += new MouseButtonEventHandler(CornerClickEvt[i]); } imgOri.ImageSource = BitmapSrcConvert.ToBitmapSource(Core.OriginImg); }
public override void OnApplyTemplate() { base.OnApplyTemplate(); Content = image = new Image(); // If the display properties is set to 125%, M11 and M22 will be 1.25. var factorX = matrix.M11; var factorY = matrix.M22; var scaleX = 1 / factorX; var scaleY = 1 / factorY; image.LayoutTransform = new ScaleTransform(scaleX, scaleY); popup = CreatePopup(); AddSourceHookIfNotAlreadyPresent(); RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor); image.Stretch = Stretch.None; image.HorizontalAlignment = HorizontalAlignment.Left; image.VerticalAlignment = VerticalAlignment.Top; }
private async Task <BitmapImage> GetNextPhotoBitmap() { CurrentIndex++; var url = _photos[CurrentIndex].Url; var aspectRatio = _photos[CurrentIndex].AspectRatio; var cancellationToken = new CancellationToken(); var httpStream = await GetBitmapStream(url); cancellationToken.ThrowIfCancellationRequested(); // calculate the actaul render (pixels) size. Idpendant of download size int widthPixels, heightPixels; if (aspectRatio >= 1.0) { widthPixels = (int)(_maxRenderWidth / RadomPhotoScale()); heightPixels = (int)(widthPixels / aspectRatio); } else { heightPixels = (int)(_maxRenderHeight / RadomPhotoScale()); widthPixels = (int)(heightPixels * aspectRatio); } var bitmap = new BitmapImage(); RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant); bitmap.BeginInit(); bitmap.DecodePixelWidth = widthPixels; bitmap.DecodePixelHeight = heightPixels; bitmap.StreamSource = httpStream; bitmap.EndInit(); return(bitmap); }
public BarSimulatorWindow(Configuration config) { this.InitializeComponent(); this.config = config; this.rect = new Int32Rect(0, 0, 760, 280); this.bitmap = new WriteableBitmap( this.rect.Width, this.rect.Height, 96, 96, PixelFormats.Bgra32, null ); byte[] pixels = new byte[this.rect.Width * this.rect.Height * 4]; for (int x = 0; x < this.rect.Width; x++) { for (int y = 0; y < this.rect.Height; y++) { int pos = (y * this.rect.Width + x) * 4; pixels[pos] = 0x00; pixels[pos + 1] = 0x00; pixels[pos + 2] = 0x00; pixels[pos + 3] = 0xFF; } } this.bitmap.WritePixels(this.rect, pixels, this.rect.Width * 4, 0); RenderOptions.SetBitmapScalingMode( this.image, BitmapScalingMode.NearestNeighbor ); RenderOptions.SetEdgeMode( this.image, EdgeMode.Aliased ); }
public override void Execute(TabItem contextViewModel, object parameter) { if (parameter == null || !contextViewModel.HasImage) { return; } switch (parameter) { case "Open": { Helper.OpenWindow <AdonisWindow>(contextViewModel.Header + " (Image)", () => { var popout = new ImagePopout { Title = contextViewModel.Header + " (Image)", Width = contextViewModel.Image.Width, Height = contextViewModel.Image.Height, WindowState = contextViewModel.Image.Height > 1000 ? WindowState.Maximized : WindowState.Normal, ImageCtrl = { Source = contextViewModel.Image } }; RenderOptions.SetBitmapScalingMode(popout.ImageCtrl, BoolToRenderModeConverter.Instance.Convert(contextViewModel.RenderNearestNeighbor)); popout.Show(); }); break; } case "Copy": ClipboardExtensions.SetImage(contextViewModel.ImageBuffer, Path.ChangeExtension(contextViewModel.Header, ".png")); break; case "Save": contextViewModel.SaveImage(false); break; } }
public void AddImage(MainWindow win, string inName, int inRow, int inColumn) { Image img = new Image(); BitmapImage bitImg = new BitmapImage(); bitImg.BeginInit(); var path = Path.Combine(Environment.CurrentDirectory + inName); bitImg.UriSource = new Uri(path); bitImg.EndInit(); img.Source = bitImg; img.Stretch = Stretch.Uniform; img.Width = winCellSize; img.Height = winCellSize; img.IsHitTestVisible = false; img.Margin = new Thickness(0); Grid.SetRow(img, inRow); Grid.SetColumn(img, inColumn); RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.NearestNeighbor); if (img.Source != null) { win.maingrid.Children.Add(img); } }
public RobotHrSp(List <string> name, List <string> infos, List <string> url) { try { InitializeComponent(); RenderOptions.SetBitmapScalingMode(Image, BitmapScalingMode.Fant); IName.Text = name[0]; IName1.Text = name[1]; IName2.Text = name[2]; IName3.Text = name[3]; IName4.Text = name[4]; info.Text = infos[0]; info1.Text = infos[1]; info2.Text = infos[2]; info3.Text = infos[3]; info4.Text = infos[4]; c.ToolTip = url[0]; c1.ToolTip = url[1]; c2.ToolTip = url[2]; c3.ToolTip = url[3]; c4.ToolTip = url[4]; } catch { } }
private ImageSource CreateResizedImage(ImageSource source, int width, int height) { var group = new DrawingGroup(); RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality); group.Children.Add(new ImageDrawing() { ImageSource = source }); var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) drawingContext.DrawDrawing(group); var resizedImage = new RenderTargetBitmap( width, height, // Resized dimensions 96, 96, // Default DPI values PixelFormats.Default); // Default pixel format resizedImage.Render(drawingVisual); return(resizedImage); }
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.LowQuality); RenderOptions.SetCachingHint(this, CachingHint.Cache); //Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline), // new FrameworkPropertyMetadata { DefaultValue = 24 }); // Default is 60. // Use desktop screenshot as a window background instead set the window transparency to true, // that will causing a poor performance. WindowBackground = new ScreenCapture(0, 0, (int)ScreenWidth, (int)ScreenHeight); ImgLoader = new ImageLoader(Properties.Settings.Default.ImagePath); GetSetImage(); Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { Timer = new DispatcherTimer() { Interval = TimeSpan.FromMinutes(1), IsEnabled = false }; Timer.Tick += delegate { PlayShow(); }; })); MoveBack = (Storyboard)Resources["MoveBack"]; MoveUp = (Storyboard)Resources["MoveUp"]; FadeIn = (Storyboard)Resources["FadeIn"]; FadeOut = (Storyboard)Resources["FadeOut"]; MoveBack.Completed += MoveBack_Completed; MoveUp.Completed += MoveUp_Completed; this.Loaded += MainWindow_Loaded; RootPanel.MouseLeftButtonDown += RootPanel_MouseLeftButtonDown; RootPanel.MouseLeftButtonUp += RootPanel_MouseLeftButtonUp; }
private async void GenerateResults() { int numberOfDays = DateTime.DaysInMonth(dateTime.Year, dateTime.Month); var start = GetStart(); int current = 1; for (int week = 1; week < 6; week++) { for (int day = 0; day < 7; day++) { ScheduleDay sd = null; if ((!(day < start) || week != 1) && current <= numberOfDays) { dateTime = new DateTime(dateTime.Year, dateTime.Month, current); var eps = episodes.Where(x => Helper.ParseAirDate(x.Key.firstAired).Day == dateTime.Day).ToDictionary(x => x.Key, x => x.Value); sd = new ScheduleDay(eps); int count = 0; var se = eps.GroupBy(s => s.Value).Select(g => g.First()).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); foreach (var s in se) { RowDefinition row = new RowDefinition(); sd.BaseGrid.RowDefinitions.Add(row); await Task.Run(async() => { var bmp = await Database.GetBanner(s.Value.id); Dispatcher.Invoke(() => { Grid grid = new Grid(); grid.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#88000000")); grid.MouseLeftButtonUp += (sx, ev) => { MainWindow.SetPage(new SeriesEpisodes(s.Value)); }; grid.ToolTip = s.Value.seriesName + " - " + Helper.GenerateName(s.Key); grid.MouseEnter += (sx, ev) => { grid.BeginStoryboard((Storyboard)FindResource("OpacityDown")); Mouse.OverrideCursor = Cursors.Hand; }; grid.MouseLeave += (sx, ev) => { grid.BeginStoryboard((Storyboard)FindResource("OpacityUp")); Mouse.OverrideCursor = null; }; Image img = new Image(); RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.HighQuality); img.Stretch = Stretch.UniformToFill; img.HorizontalAlignment = HorizontalAlignment.Center; img.Source = bmp; if (s.Key.airedEpisodeNumber == 1) { Grid grd = new Grid(); grd.Background = (Brush)FindResource("AccentColor"); sd.BaseGrid.Children.Add(grd); Grid.SetRow(grd, count); grid.ToolTip = s.Value.seriesName + " - " + Helper.GenerateName(s.Key) + " (NEW SEASON)"; img.Margin = new Thickness(2); } sd.BaseGrid.Children.Add(img); sd.BaseGrid.Children.Add(grid); Grid.SetRow(grid, count); Grid.SetRow(img, count); }); }); count++; } sd.Day.Text = current.ToString(); current++; } else { sd = new ScheduleDay(); } BaseCalendar.Children.Add(sd); Grid.SetRow(sd, week); Grid.SetColumn(sd, day); } } }
private void refreshImages() { tootText_TextChanged(null, null); if (imageFileNames.Count == 0) { this.Height = 200 + addedHeight; } else if (imageFileNames.Count > 2) { this.Height = 405 + addedHeight; } else { this.Height = 300 + addedHeight; } tootImages.Margin = new Thickness(0, 134 + addedHeight, 0, 0); //this.replyPreviewCell.Margin = new Thickness(0, tootBackground.Height + 5, 10, 0); if (imageFileNames.Count >= 4) { imageSelector.IsEnabled = false; } else { imageSelector.IsEnabled = true; } if (imageFileNames.Count == 0) { tootImages.Visibility = Visibility.Collapsed; } else { tootImages.Visibility = Visibility.Visible; } while (tootImages.Children.Count > 0) { tootImages.Children.RemoveAt(0); } int i = 0; foreach (String fileName in imageFileNames) { int x = 5; int y = 0; if (i == 1 || i == 3) { x = 160; } if (i > 1) { y = 105; } Image image = new Image(); image.HorizontalAlignment = HorizontalAlignment.Left; image.VerticalAlignment = VerticalAlignment.Top; image.Margin = new Thickness(x, y, 0, 0); image.Width = 150; image.Height = 100; image.Stretch = Stretch.UniformToFill; image.Source = new BitmapImage(new Uri(fileName)); tootImages.Children.Add(image); Button deleteBtn = new Button(); deleteBtn.HorizontalAlignment = HorizontalAlignment.Left; deleteBtn.VerticalAlignment = VerticalAlignment.Top; deleteBtn.Width = 20; deleteBtn.Height = 20; deleteBtn.Margin = new Thickness(x + 128, y + 2, 0, 0); deleteBtn.Style = Resources["FlatButton"] as Style; deleteBtn.DataContext = fileName; deleteBtn.Click += DeleteBtn_Click; deleteBtn.Cursor = Cursors.Hand; Image deleteBtnImage = new Image(); deleteBtnImage.Source = new BitmapImage(new Uri("Resources/remove.png", UriKind.Relative)); RenderOptions.SetBitmapScalingMode(deleteBtnImage, BitmapScalingMode.HighQuality); deleteBtn.Content = deleteBtnImage; tootImages.Children.Add(deleteBtn); i++; } }
private static ImageSource CreateBanner(ThumbnailBannerGeneratorData data) { Brush backgroundBrush = new SolidColorBrush(Color.FromRgb(0xF0, 0xF0, 0xF0)); Brush shadowBrush = Brushes.Black; Brush borderBrush = Brushes.Black; double shadowOpacity = 0.5; double textOpacity = 0.7; int shadowOffset = 4; int headerHeight = 95; int horizontalSpacing = 8; int verticalSpacing = 8; int positionTextOutlineWidth = 4; int textSpacing = 5; int fontSize = 16; int borderWidth = 1; string font = "Arial"; // ------------------------------ int horizontalImageResolution = ((BitmapSource)data.Images[0].Image).PixelWidth; int verticalImageResolution = ((BitmapSource)data.Images[0].Image).PixelHeight; int imageWidth = (data.Settings.TotalWidth - (data.Settings.Columns + 1) * horizontalSpacing) / data.Settings.Columns; int imageHeight = (int)Math.Round((imageWidth / (double)horizontalImageResolution) * verticalImageResolution); int width = data.Settings.TotalWidth; int height = headerHeight + (data.Settings.Rows + 1) * verticalSpacing + data.Settings.Rows * imageHeight; Typeface typefaceBold = new Typeface(new FontFamily(font), new FontStyle(), FontWeights.Bold, FontStretches.Normal); Typeface typefaceNormal = new Typeface(new FontFamily(font), new FontStyle(), FontWeights.Normal, FontStretches.Normal); ImageSource logo = new BitmapImage(new Uri("pack://application:,,,/Images/ScriptPlayerIcon.png", UriKind.RelativeOrAbsolute)); DrawingVisual image = new DrawingVisual(); using (DrawingContext dc = image.RenderOpen()) { RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.LowQuality); dc.DrawRectangle(backgroundBrush, null, new Rect(0, 0, width, height)); dc.DrawText(CreateText(Path.GetFileName(data.VideoName), typefaceBold, 18), new Point(horizontalSpacing, verticalSpacing)); string infoText = string.Format(CultureInfo.InvariantCulture, "File Size: {0}\r\n", MakeReadable(data.FileSize)) + string.Format(CultureInfo.InvariantCulture, "Resolution: {0}\r\n", data.VideoInfo.Resolution) + string.Format(CultureInfo.InvariantCulture, "Duration: {0:hh\\:mm\\:ss\\.f}", data.VideoInfo.Duration); dc.DrawText(CreateText(infoText, typefaceNormal, 16), new Point(horizontalSpacing, verticalSpacing + 25)); double logoSize = headerHeight - 2 * verticalSpacing; Rect logoDest = new Rect(width - logoSize - horizontalSpacing, verticalSpacing, logoSize, logoSize); dc.DrawImage(logo, logoDest); for (int column = 0; column < data.Settings.Columns; column++) { for (int row = 0; row < data.Settings.Rows; row++) { int index = row * data.Settings.Columns + column; int x = horizontalSpacing + column * (horizontalSpacing + imageWidth); int y = headerHeight + verticalSpacing + row * (verticalSpacing + imageHeight); Rect imageRect = new Rect(x, y, imageWidth, imageHeight); Rect borderRect = imageRect; borderRect.X -= borderWidth; borderRect.Y -= borderWidth; borderRect.Width += 2 * borderWidth; borderRect.Height += 2 * borderWidth; Rect shadowRect = borderRect; shadowRect.Offset(shadowOffset, shadowOffset); dc.PushOpacity(shadowOpacity); dc.DrawRectangle(shadowBrush, null, shadowRect); dc.Pop(); dc.DrawRectangle(borderBrush, null, borderRect); dc.DrawImage(data.Images[index].Image, imageRect); FormattedText text = CreateText(data.Images[index].Position.ToString("mm\\:ss"), typefaceBold, fontSize); Point origin = new Point(x + imageWidth - textSpacing - text.Width, y + imageHeight - textSpacing - text.Height); Geometry textGeometry = text.BuildGeometry(origin); Geometry textOutline = textGeometry.GetWidenedPathGeometry(new Pen(Brushes.Black, positionTextOutlineWidth)); dc.PushOpacity(textOpacity); dc.DrawGeometry(Brushes.Black, null, textOutline); dc.DrawGeometry(Brushes.White, null, textGeometry); dc.Pop(); } } } RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); bitmap.Render(image); return(bitmap); }
//private StackPanel GetTitle() //{ // return ((Content as StackPanel).Children[0] as Border).Child as StackPanel; // //if (OnlyTitle) // //{ // // return (((Content as StackPanel).Children[0] as Border).Child as DockPanel).Children[1] as StackPanel; // //} // //else { // // return // //} //} private void AddParentPanel() { StackPanel sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; sp.Margin = new Thickness(20, 0, 20, 0); StackPanel spTopImage = new StackPanel(); spTopImage.VerticalAlignment = VerticalAlignment.Center; spTopImage.Orientation = Orientation.Horizontal; Image image = new Image { Width = 18, Margin = new Thickness(0, 0, 10, 0), VerticalAlignment = VerticalAlignment.Center, Source = new BitmapImage(new Uri("pack://application:,,,/View/Resources/Image/move.png", UriKind.RelativeOrAbsolute)) }; image.MouseLeftButtonDown += BaseStyle_MouseMove; Image image3 = new Image { Width = 18, Margin = new Thickness(0, 0, 10, 0), VerticalAlignment = VerticalAlignment.Center, Source = new BitmapImage(new Uri("pack://application:,,,/View/Resources/Image/more_two_white.png", UriKind.RelativeOrAbsolute)) }; image3.MouseLeftButtonUp += Image3_MouseLeftButtonDown; ContextMenu contextMenu = new ContextMenu(); image3.ContextMenu = contextMenu; MenuItem menuItem = new MenuItem(); menuItem.SetResourceReference(HeaderedItemsControl.HeaderProperty, "Delete"); menuItem.Click += MenuItem_Click; contextMenu.Items.Add(menuItem); spTopImage.Children.Add(image); spTopImage.Children.Add(image3); RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality); RenderOptions.SetBitmapScalingMode(image3, BitmapScalingMode.HighQuality); sp.Children.Add(spTopImage); StackPanel spTitle = new StackPanel(); spTitle.Orientation = Orientation.Vertical; sp.Children.Add(spTitle); Border borderBottom = new Border(); borderBottom.HorizontalAlignment = HorizontalAlignment.Stretch; borderBottom.VerticalAlignment = VerticalAlignment.Center; borderBottom.CornerRadius = new CornerRadius(0, 0, 5, 5); spContacts.Orientation = Orientation.Vertical; spContacts.Margin = new Thickness(10); borderBottom.Child = spContacts; sp.Children.Add(borderBottom); AddChild(sp); }
private void ShowAllOwnedGames() { if (_ownedGames.Count > 0) { libraryEmptyMessage.Visibility = Visibility.Hidden; libraryEmptyMessage2.Visibility = Visibility.Hidden; } else { libraryTitle.Visibility = Visibility.Hidden; } double left = -1000; double top = 75; if (_ownedGames.Count >= 1) { _printedGames.Add(new Image() { Name = "game_0", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(left, top, 0, 0), Width = 250, Height = 200, Stretch = Stretch.Fill }); try { _printedGames[0].Source = new BitmapImage(new Uri(_ownedGames[0].main_img_link, UriKind.Absolute)); } catch (Exception e) { _printedGames[0].Source = _placeholderImage; } RenderOptions.SetBitmapScalingMode(_printedGames[0], BitmapScalingMode.Fant); _printedGames[0].AddHandler(MouseDownEvent, new RoutedEventHandler(GameClick)); libraryPage.Children.Add(_printedGames[0]); } int k = 1; int j = 1; int maxColumns; int maxRows = 1; if (_ownedGames.Count > 1) { if (_ownedGames.Count < 5) { maxColumns = _ownedGames.Count; } else { maxColumns = 5; } if (_ownedGames.Count > 5) { maxRows = 2; } for (int i = 0; i < maxRows; i++) { while (j < maxColumns) { left += 499; _printedGames.Add(new Image() { Name = "game_" + k, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(left, top, 0, 0), Width = 250, Height = 200, Stretch = Stretch.Fill }); try { _printedGames[k].Source = new BitmapImage(new Uri(_ownedGames[k].main_img_link, UriKind.Absolute)); } catch (Exception e) { _printedGames[k].Source = _placeholderImage; } RenderOptions.SetBitmapScalingMode(_printedGames[k], BitmapScalingMode.Fant); _printedGames[k].AddHandler(MouseDownEvent, new RoutedEventHandler(GameClick)); libraryPage.Children.Add(_printedGames[k]); k++; j++; } j = 0; left = -1499; top += 300; } } _forwardIndex = k; HidePlaceholders(); }
//shows the map for a list of airport with specific coordinates in focus private void showMap(List <Airport> airports, int zoom, GeoCoordinate focused) { double px, py; if (focused != null) { Point pos = UIHelpers.WorldToTilePos(focused, zoom); px = Math.Max(1, pos.X); py = Math.Max(1, pos.Y); } else { px = 1; py = 1; } Canvas panelMap = new Canvas(); Canvas panelMainMap = new Canvas(); panelMainMap.Width = 2 * ImageSize; for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { string name = string.Format(@"{0}\{1}\{2}.png", zoom, x - 1 + (int)px, y - 1 + (int)py); Image imgMap = new Image(); imgMap.Width = ImageSize; imgMap.Height = ImageSize; imgMap.Source = new BitmapImage(new Uri(AppSettings.getDataPath() + "\\graphics\\maps\\" + name, UriKind.RelativeOrAbsolute)); RenderOptions.SetBitmapScalingMode(imgMap, BitmapScalingMode.HighQuality); Canvas.SetTop(imgMap, y * ImageSize); Canvas.SetLeft(imgMap, x * ImageSize); panelMainMap.Children.Add(imgMap); } } ScaleTransform transform = new ScaleTransform(); transform.ScaleX = 1.5; transform.ScaleY = 1.5; panelMainMap.RenderTransform = transform; StackPanel sidePanel = createAirportSizeSidePanel(); Canvas.SetTop(sidePanel, 0); Canvas.SetLeft(sidePanel, this.MapSize); panelMap.Children.Add(panelMainMap); panelMap.Children.Add(sidePanel); foreach (Airport airport in airports) { showAirport(airport, panelMainMap, zoom, new Point((int)px - 1, (int)py - 1)); } this.Content = panelMap; }
/// <summary> /// Handles the ContextMenuOpening event of the listView control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Controls.ContextMenuEventArgs"/> instance containing the event data.</param> private void ListViewContextMenuOpening(object sender, ContextMenuEventArgs e) { e.Handled = true; if (listView.SelectedIndex == -1) { return; } var cm = new ContextMenu(); ((FrameworkElement)e.Source).ContextMenu = cm; var sub = (Subtitle)listView.SelectedValue; if (!string.IsNullOrWhiteSpace(sub.InfoURL)) { var oib = new MenuItem(); oib.Header = "Open details in browser"; oib.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/page.png")) }; oib.Click += (s, r) => Utils.Run(sub.InfoURL); cm.Items.Add(oib); } if (!string.IsNullOrWhiteSpace(sub.FileURL)) { var oib = new MenuItem(); oib.Header = "Download subtitle in browser"; oib.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/page-dl.png")) }; oib.Click += (s, r) => Utils.Run(sub.FileURL); cm.Items.Add(oib); } if (!string.IsNullOrWhiteSpace(sub.FileURL) || !(sub.Source.Downloader is ExternalDownloader)) { var dls = new MenuItem(); dls.Header = "Download subtitle"; dls.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/torrents.png")) }; dls.Click += DownloadSubtitleClick; cm.Items.Add(dls); } if (Signature.IsActivated && (!string.IsNullOrWhiteSpace(sub.FileURL) || !(sub.Source.Downloader is ExternalDownloader))) { HashSet <string> fn; if (_dbep != null && Library.Files.TryGetValue(_dbep.ID, out fn) && fn.Count != 0) { var dnv = new MenuItem(); dnv.Header = "Download subtitle near"; dnv.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/inbox-download.png")) }; cm.Items.Add(dnv); foreach (var file in fn.OrderByDescending(FileNames.Parser.ParseQuality)) { BitmapSource bmp; try { var ext = Path.GetExtension(file); if (string.IsNullOrWhiteSpace(ext)) { throw new Exception(); } var ico = Utils.Icons.GetFileIcon(ext, Utils.Icons.SHGFI_SMALLICON); if (ico == null || ico.Handle == IntPtr.Zero) { throw new Exception(); } bmp = Imaging.CreateBitmapSourceFromHBitmap(ico.ToBitmap().GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Exception) { bmp = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/film-timeline.png")); } var plf = new MenuItem(); plf.Icon = new Image { Source = bmp, Height = 16, Width = 16 }; plf.Tag = file; plf.Header = Path.GetFileName(file); plf.Click += DownloadSubtitleNearVideoClick; dnv.Items.Add(plf); } } } else if (!string.IsNullOrWhiteSpace(sub.FileURL) || !(sub.Source.Downloader is ExternalDownloader)) { var dnv = new MenuItem(); dnv.Header = "Download subtitle near video"; dnv.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/RSTVShowTracker;component/Images/inbox-download.png")) }; dnv.Click += DownloadSubtitleNearVideoClick; cm.Items.Add(dnv); } foreach (var dlcm in Extensibility.GetNewInstances <SubtitleContextMenu>()) { foreach (var dlcmi in dlcm.GetMenuItems(sub)) { var cmi = new MenuItem(); cmi.Tag = dlcmi; cmi.Header = dlcmi.Name; cmi.Icon = dlcmi.Icon; cmi.Click += (s, r) => ((ContextMenuItem <Subtitle>)cmi.Tag).Click(sub); cm.Items.Add(cmi); } } TextOptions.SetTextFormattingMode(cm, TextFormattingMode.Display); TextOptions.SetTextRenderingMode(cm, TextRenderingMode.ClearType); RenderOptions.SetBitmapScalingMode(cm, BitmapScalingMode.HighQuality); cm.IsOpen = true; }
public void Run() { var renderLoop = DataContext.CastTo <IRenderLoop>(); var reactor = renderLoop?.CurrentReactor; if (reactor == null) { mBitmap = null; return; } var width = (int)ActualWidth; var height = (int)ActualHeight; mBitmap = new WriteableBitmap(width, height, 96.0, 96.0, PixelFormats.Bgra32, null); reactor.SetBackBuffer(new MemoryWindow(mBitmap.BackBuffer, mBitmap.BackBufferStride * mBitmap.PixelHeight), TextureFormat.Bgra, mBitmap.BackBufferStride); var border = new Grid { Background = Background }; var image = new Image(); RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor); RenderOptions.SetEdgeMode(image, EdgeMode.Aliased); image.Source = mBitmap; image.Stretch = Stretch.None; image.HorizontalAlignment = HorizontalAlignment.Center; image.VerticalAlignment = VerticalAlignment.Center; border.Children.Add(image); Content = border; renderLoop.Reset(); var dt = new DispatcherTimer( TimeSpan.FromMilliseconds(1000 / 60.0), DispatcherPriority.Background, // ReSharper disable once AssignNullToNotNullAttribute dispatcher: Dispatcher, callback: (o, e) => { mBitmap.Lock(); renderLoop.NextFrame(); mBitmap.AddDirtyRect(new Int32Rect(0, 0, mBitmap.PixelWidth, mBitmap.PixelHeight)); mBitmap.Unlock(); }); dt.Start(); var infoBlock = new StackPanel(); infoBlock.SetBinding(TextBlock.FontFamilyProperty, new Binding(nameof(MeasuresFontFamily)) { Source = this, Mode = BindingMode.OneWay }); infoBlock.SetBinding(TextBlock.FontSizeProperty, new Binding(nameof(MeasuresFontSize)) { Source = this, Mode = BindingMode.OneWay }); infoBlock.SetBinding(TextBlock.ForegroundProperty, new Binding(nameof(MeasuresForeground)) { Source = this, Mode = BindingMode.OneWay }); infoBlock.SetBinding(TextBlock.BackgroundProperty, new Binding(nameof(MeasuresBackground)) { Source = this, Mode = BindingMode.OneWay }); infoBlock.Margin = new Thickness(5, 5, 0, 0); infoBlock.HorizontalAlignment = HorizontalAlignment.Left; infoBlock.VerticalAlignment = VerticalAlignment.Top; border.Children.Add(infoBlock); var fps = new TextBlock(); fps.SetBinding(VisibilityProperty, new Binding(nameof(ShowFramesPerSecond)) { Source = this, Converter = new BooleanToVisibilityConverter(), Mode = BindingMode.OneWay }); fps.SetBinding(TextBlock.TextProperty, new Binding(nameof(IRenderLoop.FramesPerSecond)) { StringFormat = "{0:###,###,###,##0.00} fps", Mode = BindingMode.OneWay }); infoBlock.Children.Add(fps); var clock = new TextBlock(); clock.SetBinding(VisibilityProperty, new Binding(nameof(ShowClock)) { Source = this, Converter = new BooleanToVisibilityConverter(), Mode = BindingMode.OneWay }); clock.SetBinding(TextBlock.TextProperty, new Binding(nameof(IRenderLoop.Clock)) { StringFormat = "{0:###,###,###,##0.00} s", Mode = BindingMode.OneWay }); infoBlock.Children.Add(clock); }
public PageNewAirline() { InitializeComponent(); StackPanel panelContent = new StackPanel(); panelContent.Margin = new Thickness(10, 0, 10, 0); panelContent.HorizontalAlignment = System.Windows.HorizontalAlignment.Center; Panel panelLogo = UICreator.CreateGameLogo(); panelLogo.Margin = new Thickness(0, 0, 0, 20); panelContent.Children.Add(panelLogo); TextBlock txtHeader = new TextBlock(); txtHeader.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; txtHeader.SetResourceReference(TextBlock.BackgroundProperty, "HeaderBackgroundBrush2"); txtHeader.FontWeight = FontWeights.Bold; txtHeader.Text = "Airline Profile"; panelContent.Children.Add(txtHeader); ListBox lbContent = new ListBox(); lbContent.ItemContainerStyleSelector = new ListBoxItemStyleSelector(); lbContent.SetResourceReference(ListBox.ItemTemplateProperty, "QuickInfoItem"); panelContent.Children.Add(lbContent); txtAirlineName = new TextBox(); txtAirlineName.Background = Brushes.Transparent; txtAirlineName.BorderBrush = Brushes.Black; txtAirlineName.Width = 200; txtAirlineName.TextChanged += new TextChangedEventHandler(txtIATA_TextChanged); lbContent.Items.Add(new QuickInfoValue("Airline Name", txtAirlineName)); txtIATA = new TextBox(); txtIATA.Background = Brushes.Transparent; txtIATA.BorderBrush = Brushes.Black; txtIATA.MaxLength = 2; txtIATA.Width = 25; txtIATA.TextChanged += new TextChangedEventHandler(txtIATA_TextChanged); lbContent.Items.Add(new QuickInfoValue("IATA Code", txtIATA)); // chs, 2011-20-10 changed to enable loading of logo WrapPanel panelAirlinerType = new WrapPanel(); RadioButton rbPassenger = new RadioButton(); rbPassenger.Content = "Passenger"; rbPassenger.GroupName = "AirlineFocus"; rbPassenger.IsChecked = true; rbPassenger.Tag = Route.RouteType.Passenger; rbPassenger.Checked += rbAirlineType_Checked; rbPassenger.Margin = new Thickness(5, 0, 0, 0); panelAirlinerType.Children.Add(rbPassenger); RadioButton rbCargo = new RadioButton(); rbCargo.Content = "Cargo"; rbCargo.GroupName = "AirlineFocus"; rbCargo.Tag = Route.RouteType.Cargo; rbCargo.Checked += rbAirlineType_Checked; panelAirlinerType.Children.Add(rbCargo); lbContent.Items.Add(new QuickInfoValue("Airline type", panelAirlinerType)); WrapPanel panelAirlineLogo = new WrapPanel(); imgLogo = new Image(); imgLogo.Source = new BitmapImage(new Uri(logoPath, UriKind.RelativeOrAbsolute)); imgLogo.Width = 32; imgLogo.Margin = new Thickness(0, 0, 5, 0); imgLogo.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; RenderOptions.SetBitmapScalingMode(imgLogo, BitmapScalingMode.HighQuality); panelAirlineLogo.Children.Add(imgLogo); Button btnLogo = new Button(); btnLogo.Content = "..."; btnLogo.Background = Brushes.Transparent; btnLogo.Click += new RoutedEventHandler(btnLogo_Click); btnLogo.Margin = new Thickness(5, 0, 0, 0); panelAirlineLogo.Children.Add(btnLogo); lbContent.Items.Add(new QuickInfoValue("Airline Logo", panelAirlineLogo)); cbColor = new ComboBox(); cbColor.SetResourceReference(ComboBox.StyleProperty, "ComboBoxTransparentStyle"); cbColor.Width = 250; cbColor.ItemTemplate = this.Resources["ColorItem"] as DataTemplate; foreach (PropertyInfo c in typeof(Colors).GetProperties()) { cbColor.Items.Add(c); } cbColor.SelectedIndex = 0; lbContent.Items.Add(new QuickInfoValue("Airline Color", cbColor)); cbCountry = new ComboBox(); cbCountry.SetResourceReference(ComboBox.StyleProperty, "ComboBoxTransparentStyle"); cbCountry.SetResourceReference(ComboBox.ItemTemplateProperty, "CountryFlagLongItem"); cbCountry.Width = 250; List <Country> countries = Countries.GetCountries(); countries.Sort(delegate(Country c1, Country c2) { return(c1.Name.CompareTo(c2.Name)); }); foreach (Country country in countries) { cbCountry.Items.Add(country); } cbCountry.SelectedItem = Countries.GetCountry("122"); lbContent.Items.Add(new QuickInfoValue("Country", cbCountry)); WrapPanel panelButtons = new WrapPanel(); panelButtons.Margin = new Thickness(0, 5, 0, 0); panelContent.Children.Add(panelButtons); btnCreate = new Button(); btnCreate.SetResourceReference(Button.StyleProperty, "RoundedButton"); btnCreate.Click += new RoutedEventHandler(btnCreate_Click); btnCreate.Height = Double.NaN; btnCreate.Width = Double.NaN; btnCreate.Content = "Create Airline"; btnCreate.IsEnabled = false; btnCreate.SetResourceReference(Button.BackgroundProperty, "ButtonBrush"); panelButtons.Children.Add(btnCreate); Button btnCancel = new Button(); btnCancel.SetResourceReference(Button.StyleProperty, "RoundedButton"); btnCancel.Height = Double.NaN; btnCancel.Width = Double.NaN; btnCancel.Content = "Cancel"; btnCancel.Margin = new Thickness(5, 0, 0, 0); btnCancel.SetResourceReference(Button.BackgroundProperty, "ButtonBrush"); btnCancel.Click += new RoutedEventHandler(btnCancel_Click); panelButtons.Children.Add(btnCancel); base.setTopMenu(new PageTopMenu()); base.hideNavigator(); base.hideBottomMenu(); base.setContent(panelContent); base.setHeaderContent("Create New Airline"); showPage(this); airlinerType = Route.RouteType.Passenger; }
private void ChangeImage() { try { var rRootGrid = (Grid)_mainWindow.Template.FindName("RootGrid", _mainWindow); if (rRootGrid != null) { foreach (UIElement el in rRootGrid.Children) { if (el.GetType() != typeof(Image)) { continue; } if (_current == null) { _current = el as Image; } if (_settings.ImageBackgroundType == ImageBackgroundType.Single || !_settings.ExpandToIDE) { rRootGrid.Children.Remove(el); _current = null; } break; } if (!_settings.ExpandToIDE) { return; } var newimage = _imageProvider.GetBitmap(); if (_settings.ImageBackgroundType == ImageBackgroundType.Single || _current == null) { var rImageControl = new Image() { Source = newimage, Stretch = _settings.ImageStretch.ConvertTo(), HorizontalAlignment = _settings.PositionHorizon.ConvertToHorizontalAlignment(), VerticalAlignment = _settings.PositionVertical.ConvertToVerticalAlignment(), Opacity = _settings.Opacity }; Grid.SetRowSpan(rImageControl, 4); RenderOptions.SetBitmapScalingMode(rImageControl, BitmapScalingMode.Fant); rRootGrid.Children.Insert(0, rImageControl); // mainwindow background set to transparent var docktargets = rRootGrid.Descendants <DependencyObject>().Where(x => x.GetType().FullName == "Microsoft.VisualStudio.PlatformUI.Shell.Controls.DockTarget"); foreach (var docktarget in docktargets) { var grids = docktarget?.Descendants <Grid>(); foreach (var g in grids) { if (g == null) { continue; } var prop = g.GetType().GetProperty("Background"); var bg = prop.GetValue(g) as SolidColorBrush; if (bg == null || bg.Color.A == 0x00) { continue; } prop.SetValue(g, new SolidColorBrush(new Color() { A = 0x00, B = bg.Color.B, G = bg.Color.G, R = bg.Color.R })); } } } else { _current.AnimateImageSourceChange( newimage, (n) => { n.Stretch = _settings.ImageStretch.ConvertTo(); n.HorizontalAlignment = _settings.PositionHorizon.ConvertToHorizontalAlignment(); n.VerticalAlignment = _settings.PositionVertical.ConvertToVerticalAlignment(); }, new Helpers.AnimateImageChangeParams { FadeTime = _settings.ImageFadeAnimationInterval, TargetOpacity = _settings.Opacity } ); } } } catch { } }
private object OnConvertFont(string text) { var element = new TextBlock(); var hasFontLetter = false; RenderOptions.SetBitmapScalingMode(element, BitmapScalingMode.HighQuality); var buffer = new StringBuilder(); if (text != null) { for (int i = 0; i < text.Length; i++) { var letter = text[i]; if (letter == '\\') { if (buffer.Length > 0) { element.Inlines.Add(new Run(buffer.ToString())); buffer.Clear(); } var code = text.Substring(i + 2, 4); var codeValue = ushort.Parse(code, NumberStyles.HexNumber); if ((codeValue & 0xFC00) == 0x8C00 || (codeValue & 0xFC00) == 0x9000) { var index = codeValue & 0x3FF; hasFontLetter |= true; element.Inlines.Add(new InlineUIContainer(new Rectangle { Margin = new Thickness(0, 2, 0, -2), UseLayoutRounding = true, SnapsToDevicePixels = true, Width = 24 / 1.5, Height = 23 / 1.5, Fill = new ImageBrush { ViewboxUnits = BrushMappingMode.Absolute, Viewbox = GetViewBox(index), ImageSource = FontData } })); } else { buffer.Append($"[{code}]"); } i += 5; } else if (letter == '[') { if (text[i + 1] == 'N' && text[i + 2] == 'L' && text[i + 3] == ']') { buffer.Append(Environment.NewLine); i += 3; } else if (text[i + 1] == 'N' && text[i + 2] == ']') { buffer.Append(Environment.NewLine); i += 2; } else { buffer.Append(letter); } } else if (letter == '|') { buffer.Append(Environment.NewLine); } else { buffer.Append(letter); } } } element.Inlines.Add(new Run(buffer.ToString())); if (hasFontLetter) { //element.FontFamily = _font; } return(element); }
private void Parse(Span span) { var context = new ParseContext(span); while (true) { var token = La(1); Consume(); switch (token.TokenType) { case BbCodeLexer.TokenStartTag: ParseTag(token.Value, true, context); break; case BbCodeLexer.TokenEndTag: ParseTag(token.Value, false, context); break; case BbCodeLexer.TokenText: var parent = span; { Uri uri; string parameter; string targetName; // parse uri value for optional parameter and/or target, eg [url=cmd://foo|parameter|target] if (NavigationHelper.TryParseUriWithParameters(context.NavigateUri, out uri, out parameter, out targetName)) { var link = new Hyperlink(); if (context.IconGeometry != null) { link.TextDecorations.Clear(); } // assign ICommand instance if available, otherwise set NavigateUri ICommand command; if (Commands != null && Commands.TryGetValue(uri, out command)) { link.Command = command; link.CommandParameter = parameter; if (targetName != null) { link.CommandTarget = _source?.FindName(targetName) as IInputElement; } } else { link.NavigateUri = uri; link.TargetName = parameter; } parent = link; span.Inlines.Add(parent); } } if (context.IconGeometry != null) { var icon = new Path { Stretch = Stretch.Uniform, Data = context.IconGeometry }; icon.SetBinding(Shape.FillProperty, new Binding { Path = new PropertyPath("(TextBlock.Foreground)"), RelativeSource = new RelativeSource(RelativeSourceMode.Self), }); Logging.Debug(token.Value); var border = new Border { Background = new SolidColorBrush(Colors.Transparent), Child = icon, ToolTip = new ToolTip { Content = new TextBlock { Text = token.Value } } }; border.SetBinding(FrameworkElement.HeightProperty, new Binding { Path = new PropertyPath("(TextBlock.FontSize)"), RelativeSource = new RelativeSource(RelativeSourceMode.Self), Converter = new MultiplyConverter(), ConverterParameter = 0.7 }); border.SetBinding(FrameworkElement.WidthProperty, new Binding { Path = new PropertyPath(nameof(Border.Height)), RelativeSource = new RelativeSource(RelativeSourceMode.Self) }); parent.Inlines.Add(new InlineUIContainer { Child = border }); continue; } { string uri; double maxSize; bool expand, toolTip; FileCache cache; if (context.ImageUri?.StartsWith(@"emoji://") == true) { maxSize = 0; expand = false; toolTip = false; var provider = BbCodeBlock.OptionEmojiProvider; if (provider == null) { uri = null; cache = null; } else { var emoji = context.ImageUri.Substring(8); uri = string.Format(provider, emoji); cache = BbCodeBlock.OptionEmojiCacheDirectory == null ? null : _emojiCache ?? (_emojiCache = new FileCache(BbCodeBlock.OptionEmojiCacheDirectory)); } } else { toolTip = true; Uri temporary; string parameter; string targetName; if (NavigationHelper.TryParseUriWithParameters(context.ImageUri, out temporary, out parameter, out targetName)) { uri = temporary.OriginalString; if (double.TryParse(parameter, out maxSize)) { expand = true; } else { maxSize = double.NaN; expand = false; } cache = BbCodeBlock.OptionImageCacheDirectory == null ? null : _imageCache ?? (_imageCache = new FileCache(BbCodeBlock.OptionImageCacheDirectory)); } else { uri = null; maxSize = double.NaN; expand = false; cache = null; } } if (uri != null) { FrameworkElement image = new Image(cache) { ImageUrl = uri }; if (toolTip) { image.ToolTip = new ToolTip { Content = new TextBlock { Text = token.Value } }; } if (double.IsNaN(maxSize)) { RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.LowQuality); } else { if (Equals(maxSize, 0d)) { image.SetBinding(FrameworkElement.MaxHeightProperty, new Binding { Path = new PropertyPath(nameof(TextBlock.FontSize)), RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(TextBlock), 1), Converter = new MultiplyConverter(), }); image.Margin = new Thickness(1, -1, 1, -1); } else { image.MaxWidth = maxSize; image.MaxHeight = maxSize; } RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality); } if (expand) { image.Cursor = Cursors.Hand; image.MouseDown += (sender, args) => { args.Handled = true; BbCodeBlock.OnImageClicked(new BbCodeImageEventArgs(new Uri(uri, UriKind.RelativeOrAbsolute))); }; } var container = new InlineUIContainer { Child = image }; parent.Inlines.Add(container); continue; } } var run = context.CreateRun(token.Value); parent.Inlines.Add(run); break; case BbCodeLexer.TokenLineBreak: span.Inlines.Add(new LineBreak()); break; case BbCodeLexer.TokenAttribute: throw new ParseException(UiStrings.UnexpectedToken); case Lexer.TokenEnd: return; default: throw new ParseException(UiStrings.UnknownTokenType); } } }
public void ConstructCanvas() { Children.Clear(); Thickness margin = ScaledThicknessFactory.GetThickness(this.margin.Left, this.margin.Top, this.margin.Right, this.margin.Bottom); if (isUpgrade) { pcntDif = width / 166; numberOwnedLeft = Opt.ApResMod(0 * pcntDif); numberOwnedTop = Opt.ApResMod(161 * pcntDif); addButtonLeft = Opt.ApResMod(0 * pcntDif); addButtonTop = Opt.ApResMod(137 * pcntDif); removeButtonLeft = Opt.ApResMod(0 * pcntDif); removeButtonTop = Opt.ApResMod(193 * pcntDif); infoButtonLeft = Opt.ApResMod(0 * pcntDif); infoButtonTop = Opt.ApResMod(0 * pcntDif); } else { pcntDif = width / 292; numberOwnedLeft = Opt.ApResMod(261 * pcntDif); numberOwnedTop = Opt.ApResMod(141 * pcntDif); addButtonLeft = Opt.ApResMod(260 * pcntDif); addButtonTop = Opt.ApResMod(120 * pcntDif); removeButtonLeft = Opt.ApResMod(260 * pcntDif); removeButtonTop = Opt.ApResMod(170 * pcntDif); infoButtonLeft = Opt.ApResMod(0 * pcntDif); infoButtonTop = Opt.ApResMod(0 * pcntDif); } miniButtonSize = Opt.ApResMod(21); Margin = margin; Width = Opt.ApResMod(width); Height = Opt.ApResMod(height); cardImage.Width = Opt.ApResMod(width); cardImage.Height = Opt.ApResMod(height); cardImage.MouseEnter += new MouseEventHandler(MouseHover); cardImage.MouseLeave += new MouseEventHandler(MouseHoverLeave); RenderOptions.SetBitmapScalingMode(this.cardImage, BitmapScalingMode.HighQuality); SetLeft(cardImage, 0); SetTop(cardImage, 0); Children.Add(cardImage); if (isUpgrade) { numberOwned.Text = upgrade.numberOwned.ToString(); } else { numberOwned.Text = pilot.numberOwned.ToString(); } numberOwned.TextAlignment = TextAlignment.Left; numberOwned.Width = Opt.ApResMod(30 * pcntDif); numberOwned.Height = Opt.ApResMod(30 * pcntDif); numberOwned.StrokeThickness = 1; numberOwned.Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0)); numberOwned.FontWeight = FontWeights.ExtraBold; numberOwned.Fill = new SolidColorBrush(Color.FromRgb(255, 207, 76)); numberOwned.FontSize = Opt.ApResMod(22); numberOwned.FontFamily = new FontFamily("Verdana"); if (currentPage != null) { numberOwned.MouseWheel += new MouseWheelEventHandler(currentPage.ContentScroll); } numberOwned.MouseEnter += new MouseEventHandler(MouseHover); numberOwned.MouseLeave += new MouseEventHandler(MouseHoverLeave); SetLeft(numberOwned, numberOwnedLeft); SetTop(numberOwned, numberOwnedTop); Children.Add(numberOwned); }
protected override void OnRender(DrawingContext dc) { if (PointsToDisplay != null) { Log.Debug("PointsToDisplay is not empty - rendering points"); var canvasWidth = (int)ActualWidth; var canvasHeight = (int)ActualHeight; if (canvasWidth > 0 && canvasHeight > 0) { //Create the bitModeScreenCoordinateToKeyMap var wb = new WriteableBitmap(canvasWidth, canvasHeight, 96, 96, PixelFormats.Bgra32, null); //Create a new image var img = new Image { Source = wb, Stretch = Stretch.None, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }; //Set scaling mode, edge mode and z index on canvas RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.NearestNeighbor); RenderOptions.SetEdgeMode(img, EdgeMode.Aliased); SetZIndex(img, -100); //Each "dot" is 3x3 rectangle (centered on the coordinate detected) var rect = new Int32Rect(0, 0, 3, 3); int size = rect.Width * rect.Height * 4; var pixels = new byte[size]; int screenCoordinatesIndex = 0; int screenCoordinatesIndexUpperBound = PointsToDisplay.Count - 1; foreach (Point capturedCoordinate in PointsToDisplay) { Point canvasPoint = PointFromScreen(capturedCoordinate); //Convert screen to canvas point if (canvasPoint.X >= 0 && canvasPoint.X < canvasWidth && canvasPoint.Y >= 0 && canvasPoint.Y < canvasHeight) { SetPixelValuesToRainbow(pixels, rect, screenCoordinatesIndex, screenCoordinatesIndexUpperBound); //Set up pixel colours (as RGB and Alpha array of bytes) //We are drawing a 3x3 dot so try to start one pixel up and left (center pixel of rectangle will be the co-ordinate) //If coord in against the top or left side (x=0 and/or y=0) this cannot be done, so just place as close as possible //If coord in against the bottom or right side (x>=canvasWidth-1 and/or y>=canvasHeight-1) this cannot be done either, so just place as close as possible rect.X = (int)canvasPoint.X == 0 ? (int)canvasPoint.X : (int)canvasPoint.X > 0 && (int)canvasPoint.X < canvasWidth - 1 ? (int)canvasPoint.X - 1 : (int)canvasPoint.X - 2; rect.Y = (int)canvasPoint.Y == 0 ? (int)canvasPoint.Y : (int)canvasPoint.Y > 0 && (int)canvasPoint.Y < canvasHeight - 1 ? (int)canvasPoint.Y - 1 : (int)canvasPoint.Y - 2; wb.WritePixels(rect, pixels, rect.Width * 4, 0); screenCoordinatesIndex++; } } dc.DrawImage(wb, new Rect(0, 0, canvasWidth, canvasHeight)); } } else { Log.Debug("OnRender - PointsToDisplay is empty - nothing to render"); } base.OnRender(dc); }
void _config_ConfigurationUpdated(object sender, EventArgs e) { Dispatcher.InvokeAsync(() => RenderOptions.SetBitmapScalingMode(this, _config.Configuration.EnableHighQualityImageScaling ? BitmapScalingMode.Fant : BitmapScalingMode.LowQuality)); }