// public override TextExtents GetExtents(Cairo.Context cr) // { // TextExtents extents = new TextExtents(); // extents.Height = _pageSettings.PageHeight; // extents.Width = _pageSettings.PageWidth; // return extents; // } public override void Draw(Cairo.Context cr, double xPos, double yPos, PrintLayer layer) { if (layer == PrintLayer.DisplayBackground) { // Create the shadow effect cr.SetSourceRGBA(0.5, 0.5, 0.5, 0.5); cr.Rectangle(xPos + Constants.SHADOW_WIDTH , yPos + Constants.SHADOW_WIDTH , _pageSettings.PaperWidth , _pageSettings.PaperHeight); cr.Fill(); cr.SetSourceRGB(1, 1, 1); cr.Rectangle(xPos , yPos , _pageSettings.PaperWidth , _pageSettings.PaperHeight); cr.Fill(); } double pageTop = yPos; yPos += _pageSettings.TopMargin; xPos += _pageSettings.LeftMargin; if (_header != null) { yPos += _header.GetExtents(cr).Height; _header.Draw(cr, xPos, yPos, layer); } // Move the cursor to the bottom of the page elements. TextExtents extents = GetExtents(cr); yPos += extents.Height + extents.YAdvance; // Draw the page elements in reverse order. base.Draw(cr, xPos, yPos, layer); if (_footer != null) { yPos = pageTop + _pageSettings.PageHeight; _footer.Draw(cr, xPos, yPos, layer); } }
public override void Render(GraphicsContext g) { PaintBackground(g, Background); if (Foreground == null || string.IsNullOrWhiteSpace(Text)) { return; } Foreground.ApplyBrushToContext(g); g.SelectFontFace(FontFamily, FontSlant, FontWeight); g.SetFontSize(FontSize); TextExtents te = g.TextExtents(Text); g.MoveTo(te.XBearing * -1 + Padding.Left, te.YBearing * -1 + Padding.Top); g.ShowText(Text); }
protected override int measureRawSize(LayoutingType lt) { if (lines == null) { lines = getLines; } using (ImageSurface img = new ImageSurface(Format.Argb32, 10, 10)) { using (Context gr = new Context(img)) { //Cairo.FontFace cf = gr.GetContextFontFace (); gr.SelectFontFace(Font.Name, Font.Slant, Font.Wheight); gr.SetFontSize(Font.Size); fe = gr.FontExtents; te = new TextExtents(); if (lt == LayoutingType.Height) { int lc = lines.Count; //ensure minimal height = text line height if (lc == 0) { lc = 1; } return((int)Math.Ceiling(fe.Height * lc) + Margin * 2); } foreach (string s in lines) { string l = s.Replace("\t", new String(' ', Interface.TabSize)); TextExtents tmp = gr.TextExtents(l); if (tmp.XAdvance > te.XAdvance) { te = tmp; } } return((int)Math.Ceiling(te.XAdvance) + Margin * 2); } } }
//--------------------------------------------------------------------- /// <summary> /// Gets the width of the given text with the selected font. /// </summary> /// <param name="context">The <see cref="Context" /></param> /// <param name="text">The string.</param> /// <returns>The width of the text.</returns> public static double GetTextWidth(this Context context, string text) { if (text == null) { throw new ArgumentNullException(nameof(text)); } double textWidth = 0; for (int i = 0; i < text.Length; ++i) { string s = text.Substring(i, 1); TextExtents te = context.TextExtents(s); textWidth += te.XAdvance; } return(textWidth); }
protected override int measureRawSize(LayoutingType lt) { if (lines == null) { lines = getLines; } if (!textMeasureIsUpToDate) { using (ImageSurface img = new ImageSurface(Format.Argb32, 10, 10)) { using (Context gr = new Context(img)) { //Cairo.FontFace cf = gr.GetContextFontFace (); gr.SelectFontFace(Font.Name, Font.Slant, Font.Wheight); gr.SetFontSize(Font.Size); gr.FontOptions = Interface.FontRenderingOptions; gr.Antialias = Interface.Antialias; fe = gr.FontExtents; te = new TextExtents(); cachedTextSize.Height = (int)Math.Ceiling((fe.Ascent + fe.Descent) * Math.Max(1, lines.Count)) + Margin * 2; try { foreach (string s in lines) { string l = s.Replace("\t", new String(' ', Interface.TabSize)); TextExtents tmp = gr.TextExtents(l); if (tmp.XAdvance > te.XAdvance) { te = tmp; } } cachedTextSize.Width = (int)Math.Ceiling(te.XAdvance) + Margin * 2; textMeasureIsUpToDate = true; } catch { return(-1); } } } } return(lt == LayoutingType.Height ? cachedTextSize.Height : cachedTextSize.Width); }
public static Size GetSize(this string value, string fontFamily, double fontSize, FontSlant fontSlant, FontWeight fontWeight) { if (string.IsNullOrEmpty(value)) { return(new Size(0, 0)); } using (ImageSurface surface = new ImageSurface(Format.Argb32, 0, 0)) { using (GraphicsContext context = new GraphicsContext(surface)) { context.SelectFontFace(fontFamily, fontSlant, fontWeight); context.SetFontSize(fontSize); TextExtents te = context.TextExtents(value); double width = te.Width; double height = te.Height; return(new Size(width, height)); } } }
protected void OnDrawingarea2ExposeEvent(object o, ExposeEventArgs args) { DrawingArea legendDrawArea = (DrawingArea)o; legendContext = CairoHelper.Create(legendDrawArea.GdkWindow); List <int> gpuIds = new List <int> (); #if DEBUG gpuIds = new List <int> () { 0, 1, 2, 3 }; #endif int legendLabelStartX = 20; int legendLabelStartY = 20; int legendTextStartX = 20; int legendTextStartY = 50; int legendLabelLength = 50; int labelDistance = 40; //int labelToFontDistance = 15; foreach (int gpuId in gpuIds) { legendContext.SetSourceColor(chartLineColors[gpuId]); legendContext.Antialias = Antialias.Subpixel; legendContext.LineWidth = 20; legendContext.MoveTo(legendLabelStartX + gpuId * (legendLabelLength + labelDistance), legendLabelStartY); legendContext.LineTo(legendLabelStartX + gpuId * (legendLabelLength + labelDistance) + legendLabelLength, legendLabelStartY); legendContext.Stroke(); legendContext.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Bold); legendContext.SetFontSize(16); String notation = "GPU " + gpuId.ToString(); for (int i = 0; i < notation.Length; i++) { string subStr = notation.Substring(i, 1); TextExtents te = legendContext.TextExtents(subStr); legendContext.MoveTo(legendTextStartX + te.Width * i + gpuId * (labelDistance + legendLabelLength), legendTextStartY + te.Height / 2); legendContext.ShowText(subStr); } } }
/// <summary> /// Update Current Column, line and TextCursorPos /// from mouseLocalPos /// </summary> void computeTextCursor(Context gr) { TextExtents te; double cPos = 0f; CurrentLine = (int)(mouseLocalPos.Y / fe.Height); //fix cu if (CurrentLine >= lines.Count) { CurrentLine = lines.Count - 1; } for (int i = 0; i < lines[CurrentLine].Length; i++) { string c = lines [CurrentLine].Substring(i, 1); if (c == "\t") { c = new string (' ', Interface.TabSize); } te = gr.TextExtents(c); double halfWidth = te.XAdvance / 2; if (mouseLocalPos.X <= cPos + halfWidth) { CurrentColumn = i; textCursorPos = cPos; mouseLocalPos = -1; return; } cPos += te.XAdvance; } CurrentColumn = lines[CurrentLine].Length; textCursorPos = cPos; //reset mouseLocalPos mouseLocalPos = -1; }
public TextExtents MeasureText(ref TextBlock block, TextQuality quality) { // First, check if we have cached this text block. Do not use block_cache.TryGetValue, to avoid thrashing // the user's TextBlockExtents struct. int hashcode = block.GetHashCode(); if (block_cache.ContainsKey(hashcode)) { return(block_cache[hashcode]); } // If this block is not cached, we have to measure it and (potentially) place it in the cache. TextExtents extents = MeasureTextExtents(ref block, quality); if ((block.Options & TextPrinterOptions.NoCache) == 0) { block_cache.Add(hashcode, extents); } return(extents); }
public bool TryAddLine(Cairo.Context cr, BaseNode lineNode) { // If we have not yet determined the actual page height, calculate it now. if (_availablePageHeight == 0) { _availablePageHeight = _pageSettings.PageHeight; if (_header != null) { _availablePageHeight -= _header.GetExtents(cr).Height; } if (_footer != null) { _availablePageHeight -= _footer.GetExtents(cr).Height; } } // Now see if the text field will fit on our page. bool retval = false; TextExtents extents = lineNode.GetExtents(cr); if (_currentYPos + extents.Height < _availablePageHeight) { if (_currentRegion != null) { _currentRegion.AddNode(lineNode); } else { _children.Add(lineNode); } retval = true; _currentYPos += extents.Height + extents.YAdvance; } return(retval); }
/// <summary> /// Initializes a new instance of the <see cref="CSGen.Model.Renderer.LineNode"/> class. /// </summary> /// <param name="extents">The maximum dimensions for the space the line should occupy.</param> /// <param name="lineThickness">The width of the line.</param> public LineNode(double width, double height, double yAdvance, PrintLineType lineType) { _extents = new TextExtents(); switch (lineType) { case PrintLineType.Single: _lineThickness = 0.5; if (height == 0) { height = 3; } break; case PrintLineType.Double: _lineThickness = 0.5; if (height == 0) { height = 6; } break; case PrintLineType.Thick: _lineThickness = 2.0; if (height == 0) { height = 6; } break; case PrintLineType.None: break; } _extents.Width = width; _extents.Height = height; _extents.YAdvance = yAdvance; _lineType = lineType; }
PointD drawButton(Cairo.Context cr, double x, double y, String text, Boolean selected) { cr.SetSourceRGB(0, 0, 0); cr.SelectFontFace("Georgia", FontSlant.Normal, FontWeight.Bold); int grow = selected ? 3 : 0; cr.SetFontSize(11 + grow); TextExtents te = cr.TextExtents(text); int spacing = 5; DrawRoundedRectangle(cr, x - grow, y - grow, te.Width + grow * 2 + spacing * 2, TileSize + grow * 2, 3); cr.SetSourceRGB(1, 1, 1); cr.FillPreserve(); cr.SetSourceRGB(0, 0, 0); cr.LineWidth = 1.2; cr.Stroke(); cr.MoveTo( x + spacing - te.XBearing, y - te.YBearing + (TileSize - te.Height) / 2); cr.ShowText(text); if (allOffPosition.X == 0) { allOffPosition.X = (int)x; allOffPosition.Y = (int)y; allOffPosition.Width = (int)(te.Width + spacing * 2); allOffPosition.Height = TileSize; } return(new PointD(x + te.Width + spacing * 2 + TileSpacing, 0)); }
public void text_align_center(Context cr, int width, int height) { Normalize(cr, width, height); cr.SelectFontFace("Sans", FontSlant.Normal, FontWeight.Normal); cr.SetFontSize(0.2); TextExtents extents = cr.TextExtents("cairo"); double x = 0.5 - ((extents.Width / 2.0) + extents.XBearing); double y = 0.5 - ((extents.Height / 2.0) + extents.YBearing); cr.MoveTo(x, y); cr.ShowText("cairo"); // draw helping lines cr.Color = new Color(1, 0.2, 0.2, 0.6); cr.Arc(x, y, 0.05, 0, 2 * Math.PI); cr.Fill(); cr.MoveTo(0.5, 0); cr.RelLineTo(0, 1); cr.MoveTo(0, 0.5); cr.RelLineTo(1, 0); cr.Stroke(); }
protected override void DrawContents(Gdk.Drawable d, Cairo.Context g, int width, int height, bool screenChanged) { string message = Message(Timer); TextExtents te = g.TextExtents(message); Move(100, 100); Width = (int)te.Width + w_padding * 2; Height = (int)te.Height + h_padding * 2; int x = ScreenState.Width / 2 - Width / 2; int y = ScreenState.Height / 2 - Height / 2; Move(x, y); g.SelectFontFace(Text.MONOSPACE_FONT, FontSlant.Normal, FontWeight.Bold); g.SetFontSize(24); double x_text = X + Width / 2 - te.Width / 2 - te.Width; double y_text = Y + Height / 2 - te.Height / 2; Text.ShadowedText(g, message, x_text, y_text); }
protected void OnDrawingTrackExposeEvent(object o, ExposeEventArgs args) { using (Context g = Gdk.CairoHelper.Create(args.Event.Window)) { //DrawCurvedRectangle(g, 30, 30, 40, 40); //g.SetSourceColor( new Color(0.1, 0.6, 1, 1)); //g.FillPreserve(); //g.SetSourceColor( new Color(0.2, 0.8, 1, 1)); //g.LineWidth = 5; //g.Stroke(); short i = 0, k = 0; g.SelectFontFace("DejaVu Sans Mono", FontSlant.Normal, FontWeight.Normal); g.SetFontSize(14); for (k = 0; k < MainClass.tracks.MaxRow; k++) { string s = ""; s += string.Format("{0,2} ", MainClass.tracks.GetSeq(i, k)); s += string.Format("{0,3} ", MainClass.tracks.GetNote(i, k)); s += string.Format("{0:X2} ", MainClass.tracks.GetInstr(i, k)); s += string.Format("{0:X2} ", MainClass.tracks.GetCmd(i, k)); TextExtents te = g.TextExtents(s); g.MoveTo(0.5 - te.XBearing + 100 - te.Width, 0.5 - te.YBearing + y_mid + fe.Height * k); g.ShowText(s); } g.MoveTo(0, y_mid + this.TrackScrolledWindow.Vadjustment.Value); g.LineTo(100, y_mid + this.TrackScrolledWindow.Vadjustment.Value); g.Stroke(); g.Dispose(); } }
public override TextExtents GetExtents(Cairo.Context cr) { if (!_extentsDetermined) { _extentsDetermined = true; _chordExtents = _chordLine.GetHorizontalExtents(cr); _extents = _children.GetHorizontalExtents(cr); // Check to see if we need to add a word connecting line. if (_children.Count > 0 && _extents.Width < _chordExtents.Width) { TextNode textNode = (TextNode)_children[0]; if (textNode != null && _breaksWord) { _children.Add(new SpacerNode(textNode.Font, 1)); double len = _chordExtents.Width - _extents.Width - 2; if (len > 0) { LineNode lineNode = new LineNode(len, _extents.Height, _extents.YAdvance, PrintLineType.Single); _children.Add(lineNode); _extents = _children.GetHorizontalExtents(cr); } } } _totalExtents = new TextExtents(); _totalExtents.Width = Math.Max(_chordExtents.Width, _extents.Width); _totalExtents.Height = _chordExtents.Height + _chordExtents.YAdvance + _extents.Height; _totalExtents.YAdvance = _extents.YAdvance; } return(_totalExtents); }
public override void Draw(Cairo.Context surface, int x, int y) { X = x; Y = y; double StartAngle = (1 / 8) * Math.PI; double EndAngle = 2 * Math.PI - ((1 / 8) * Math.PI); lightValue = CurrentData.GetCurrentValueByIdFloat("LIGHT"); //LIGHTBULB ALL THE WAY BABY surface.MoveTo(X - 100 * scaleFactor, Y + 200 * scaleFactor); surface.LineTo(X - 100 * scaleFactor, Y - 100 * scaleFactor); surface.Arc(X, Y - 100 * scaleFactor, 200 * scaleFactor, StartAngle, EndAngle); surface.MoveTo(X + 100 * scaleFactor, Y - 100 * scaleFactor); surface.LineTo(X + 100 * scaleFactor, Y + 200 * scaleFactor); surface.LineTo(X - 100 * scaleFactor, Y + 200 * scaleFactor); surface.SetSourceRGBA(1, 1, 0, 0.20 + normalizingLightValue()); surface.Fill(); if (_showText == true) { widgetText = lightValue + ""; surface.SetFontSize(13); text = surface.TextExtents(widgetText); surface.SetSourceRGBA(0.98f, 0.5f, 0.4f, Alpha); surface.MoveTo(X - (text.Width / 2), Y + (text.Height / 2) + 15); surface.ShowText(widgetText); } }
private static void drawTile(Context c, Tile tile, int x, int y) { int value = tile.Value; int prevX = tile.Col; int prevY = tile.Row; int fromX = tile.Col * (TILE_MARGIN + TILE_SIZE) + TILE_MARGIN; int fromY = tile.Row * (TILE_MARGIN + TILE_SIZE) + TILE_MARGIN; int toX = x * (TILE_MARGIN + TILE_SIZE) + TILE_MARGIN; int toY = y * (TILE_MARGIN + TILE_SIZE) + TILE_MARGIN; int posX = 0; int posY = 0; int distanceX = Math.Abs(fromX - toX); int distanceY = Math.Abs(fromY - toY); tile.ShiftX += (((double)Window.INTERVAL * distanceX) / DURATION); tile.ShiftY += (((double)Window.INTERVAL * distanceY) / DURATION); if (tile.Animating) { bool done = false; if (prevX != x) { // horizontal moving if (prevX < x) { if ((posX = (int)(fromX + tile.ShiftX)) >= toX) { done = true; } } else if (prevX > x) { if ((posX = (int)(fromX - tile.ShiftX)) <= toX) { done = true; } } posY = toY; } else if (prevY != y) { // vertical moving if (prevY < y) { if ((posY = (int)(fromY + tile.ShiftY)) >= toY) { done = true; } } else if (prevY > y) { if ((posY = (int)(fromY - tile.ShiftY)) <= toY) { done = true; } } posX = toX; } else { Console.WriteLine("MOVE ERROR!"); } if (done) { tile.Animating = false; TilesAnimationsDone++; tile.ResetShift(); posX = toX; posY = toY; } } else { posX = toX; posY = toY; } if (value != 0) { c.SetSourceRGBA(0, 0, 1, 1); DrawRoundedRectangle(c, posX, posY, TILE_SIZE, TILE_SIZE, RADIUS); c.Fill(); int size = value < 100 ? 36 : value < 1000 ? 32 : 24; c.SetFontSize(size); c.SetSourceRGBA(1, 1, 1, 1); c.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Bold); string s = value.ToString(); TextExtents te = c.TextExtents(s); double w = te.Width; double h = te.Height; c.MoveTo(posX + ((TILE_SIZE - w) / 2 - te.XBearing), posY + TILE_SIZE - ((TILE_SIZE - h) / 2)); c.ShowText(s); } if (Game.BOARD.WonOrLost != null && Game.BOARD.WonOrLost.Length != 0) { string WonOrLost = "You " + Game.BOARD.WonOrLost; c.SetSourceRGBA(0, 0, 0, 1); c.Rectangle(0, 0, Game.WINDOW.WIDTH, Game.WINDOW.HEIGHT); //c.SetSourceRGBA(1, 1, 1, 0.5); c.Fill(); c.SetSourceRGBA(1, 1, 1, 1); //c.Fill(); c.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Normal); c.SetFontSize(30); c.MoveTo(68, 150); c.ShowText(WonOrLost); c.Fill(); } c.Fill(); }
void DrawTrack( ) { drawingarea1.GdkWindow.Clear(); // clear Background using (Context g = Gdk.CairoHelper.Create(this.drawingarea1.GdkWindow)) { short i = 0, curRow, k = 0; int y_print; g.SelectFontFace("DejaVu Sans Mono", FontSlant.Normal, FontWeight.Normal); g.SetFontSize(14); curRow = (short)vscrollbarTrack.Adjustment.Value; int upper = DisplayLines / 2; y_print = upper * (int)fe.Height; int upper2 = upper; upper2 -= curRow; if (upper2 < 0) { y_print = 0; curRow -= (short)upper; // beginnt am oberen Fensterrand } else { y_print -= (int)fe.Height * (curRow); curRow = 0; } // Console.WriteLine(j); for (k = 0; curRow <= MainClass.tracks.MaxRow; k++) { string s = ""; s += string.Format("{0,3}: ", curRow); // Zeilennummer for (i = 0; i < 3; i++) { s += string.Format("{0,2} ", MainClass.tracks.GetSeq(i, curRow)); s += string.Format("{0,3} ", MainClass.tracks.GetNote(i, curRow)); s += string.Format("{0:X2} ", MainClass.tracks.GetInstr(i, curRow)); s += string.Format("{0:X2} ", MainClass.tracks.GetCmd(i, curRow)); } curRow++; TextExtents te = g.TextExtents(s); g.MoveTo(0.5 - te.XBearing + te.XAdvance - te.Width, 0.5 - te.YBearing + y_print + fe.Height * k); Console.WriteLine(te.Width + " " + te.XAdvance); g.ShowText(s); } //g.MoveTo(0, y_start); //g.LineTo(this.drawingarea1.WidthRequest, y_start); g.Rectangle(0, upper * (int)fe.Height, this.drawingarea1.WidthRequest, fe.Height); g.SetSourceColor(new Color(1, 0, 0, 0.10)); g.Fill(); g.Stroke(); g.Dispose(); } }
private void escenarioCargado(Context cr) { // cr.SetSourceSurface(Constantes.escenarioSurface, 0, 0); // cr.Paint(); foreach (Obstaculo o in Logica.circulos) { if (o.intermitencia != 0 && (Constantes.tiempo % o.intermitencia) == 0) { o.enable = !o.enable; } if (o.enable || !Logica.play || !Constantes.simulacion) { cr.Save(); cr.LineWidth = 2; cr.SetSourceRGBA(0, 0, 1, 1); cr.Arc(o.rectangle.X, o.rectangle.Y, o.rectangle.Width, o.rectangle.Height, Math.PI * 2); cr.Stroke(); cr.Restore(); } } foreach (Obstaculo o in Logica.rectangulos) { if (o.intermitencia != 0 && (Constantes.tiempo % o.intermitencia) == 0) { o.enable = !o.enable; } if (o.enable || !Logica.play || !Constantes.simulacion) { cr.Save(); cr.Rectangle(o.rectangle.X, o.rectangle.Y, o.rectangle.Width, o.rectangle.Height); cr.LineWidth = 2; cr.SetSourceRGBA(1, 0, 0, 1); cr.Stroke(); cr.Restore(); } } foreach (Obstaculo o in Logica.lineas) { if (o.intermitencia != 0 && (Constantes.tiempo % o.intermitencia) == 0) { o.enable = !o.enable; } if (o.enable || !Logica.play || !Constantes.simulacion) { cr.Save(); cr.LineWidth = 2; cr.SetSourceRGBA(0, 1, 0, 1); cr.MoveTo(o.rectangle.X, o.rectangle.Y); cr.LineTo(o.rectangle.Width, o.rectangle.Height); cr.Stroke(); cr.Restore(); } } foreach (System.Drawing.Point p in Logica.puntos_inicio) { cr.Save(); cr.SetSourceRGBA(1, 0, 1, 0.8); cr.Arc(p.X, p.Y, 10, 0, 2 * Math.PI); cr.Fill(); cr.Stroke(); cr.Restore(); } int n = 1; foreach (Objetivo o in Logica.puntos_objetivo) { foreach (System.Drawing.Point p in o.Objetivos()) { cr.Save(); cr.SetSourceRGBA(1, 0, 0, 0.6); cr.Arc(p.X, p.Y, Constantes.radio_objetivos, 0, 2 * Math.PI); cr.Fill(); cr.Stroke(); cr.SetSourceRGB(0, 0, 0); cr.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Normal); cr.SetFontSize(12); TextExtents t = cr.TextExtents(n.ToString()); cr.MoveTo(p.X - 4, p.Y + 4); cr.ShowText(n.ToString()); cr.Restore(); } n++; } }
public void Print(ref TextBlock block, Color color, IGlyphRasterizer rasterizer) { GL.PushAttrib(AttribMask.CurrentBit | AttribMask.TextureBit | AttribMask.EnableBit | AttribMask.ColorBufferBit | AttribMask.DepthBufferBit); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); SetBlendFunction(); GL.Disable(EnableCap.DepthTest); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int)All.Modulate); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvColor, new Color4(0, 0, 0, 0)); GL.Disable(EnableCap.TextureGenQ); GL.Disable(EnableCap.TextureGenR); GL.Disable(EnableCap.TextureGenS); GL.Disable(EnableCap.TextureGenT); RectangleF position; SetColor(color); int block_hash = block.GetHashCode(); if (block_cache.ContainsKey(block_hash)) { GL.CallList(block_cache[block_hash]); } else { using (TextExtents extents = rasterizer.MeasureText(ref block)) { // Build layout int current = 0; foreach (Glyph glyph in block) { // Do not render whitespace characters or characters outside the clip rectangle. if (glyph.IsWhiteSpace || extents[current].Width == 0 || extents[current].Height == 0) { current++; continue; } else if (!Cache.Contains(glyph)) { Cache.Add(glyph, rasterizer, TextQuality); } CachedGlyphInfo info = Cache[glyph]; position = extents[current++]; // Use the real glyph width instead of the measured one (we want to achieve pixel perfect output). position.Size = info.Rectangle.Size; if (!active_lists.ContainsKey(info.Texture)) { if (inactive_lists.Count > 0) { List <Vector2> list = inactive_lists.Dequeue(); list.Clear(); active_lists.Add(info.Texture, list); } else { active_lists.Add(info.Texture, new List <Vector2>()); } } { // Interleaved array: Vertex, TexCoord, Vertex, ... List <Vector2> current_list = active_lists[info.Texture]; current_list.Add(new Vector2(info.RectangleNormalized.Left, info.RectangleNormalized.Top)); current_list.Add(new Vector2(position.Left, position.Top)); current_list.Add(new Vector2(info.RectangleNormalized.Left, info.RectangleNormalized.Bottom)); current_list.Add(new Vector2(position.Left, position.Bottom)); current_list.Add(new Vector2(info.RectangleNormalized.Right, info.RectangleNormalized.Bottom)); current_list.Add(new Vector2(position.Right, position.Bottom)); current_list.Add(new Vector2(info.RectangleNormalized.Right, info.RectangleNormalized.Bottom)); current_list.Add(new Vector2(position.Right, position.Bottom)); current_list.Add(new Vector2(info.RectangleNormalized.Right, info.RectangleNormalized.Top)); current_list.Add(new Vector2(position.Right, position.Top)); current_list.Add(new Vector2(info.RectangleNormalized.Left, info.RectangleNormalized.Top)); current_list.Add(new Vector2(position.Left, position.Top)); } } } // Render int display_list = 0; if ((block.Options & TextPrinterOptions.NoCache) == 0) { display_list = GL.GenLists(1); // Mesa Indirect gerates an InvalidOperation error right after // GL.EndList() when using ListMode.CompileAndExecute. // Using ListMode.Compile as a workaround. GL.NewList(display_list, ListMode.Compile); } foreach (Texture2D key in active_lists.Keys) { List <Vector2> list = active_lists[key]; key.Bind(); GL.Begin(BeginMode.Triangles); for (int i = 0; i < list.Count; i += 2) { GL.TexCoord2(list[i]); GL.Vertex2(list[i + 1]); } GL.End(); } if ((block.Options & TextPrinterOptions.NoCache) == 0) { GL.EndList(); block_cache.Add(block_hash, display_list); GL.CallList(display_list); } // Clean layout foreach (List <Vector2> list in active_lists.Values) { //list.Clear(); inactive_lists.Enqueue(list); } active_lists.Clear(); } GL.PopAttrib(); }
//--------------------------------------------------------------------- private static void Primitives() { Action <Surface> draw = surface => { using (var c = new Context(surface)) { c.Scale(4, 4); // Stroke: c.LineWidth = 0.1; c.Color = new Color(0, 0, 0); c.Rectangle(10, 10, 10, 10); c.Stroke(); c.Save(); { c.Color = new Color(0, 0, 0); c.Translate(20, 5); c.MoveTo(0, 0); c.LineTo(10, 5); c.Stroke(); } c.Restore(); // Fill: c.Color = new Color(0, 0, 0); c.SetSourceRGB(0, 0, 0); c.Rectangle(10, 30, 10, 10); c.Fill(); // Text: c.Color = new Color(0, 0, 0); c.SelectFontFace("Georgia", FontSlant.Normal, FontWeight.Bold); c.SetFontSize(10); TextExtents te = c.TextExtents("a"); c.MoveTo( 0.5 - te.Width / 2 - te.XBearing + 10, 0.5 - te.Height / 2 - te.YBearing + 50); c.ShowText("a"); c.Color = new Color(0, 0, 0); c.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Bold); c.SetFontSize(10); te = c.TextExtents("a"); c.MoveTo( 0.5 - te.Width / 2 - te.XBearing + 10, 0.5 - te.Height / 2 - te.YBearing + 60); c.ShowText("a"); } }; using (Surface surface = new ImageSurface(Format.Argb32, 200, 3200)) { draw(surface); surface.WriteToPng("primitives.png"); } using (Surface surface = new PdfSurface("primitives.pdf", 200, 3200)) draw(surface); using (Surface surface = new SvgSurface("primitives.svg", 200, 3200)) draw(surface); }
void ComposeButton(Context ctx, ImageSurface surface, bool pressed) { double embossHeight = scaled(2.5); if (buttonStyle == EnumButtonStyle.Normal) { embossHeight = scaled(1.5); } Bounds.CalcWorldBounds(); normalText.AutoBoxSize(true); pressedText.Bounds = normalText.Bounds.CopyOnlySize(); if (buttonStyle != EnumButtonStyle.None) { // Brown background Rectangle(ctx, Bounds.bgDrawX, Bounds.bgDrawY, Bounds.OuterWidth, Bounds.OuterHeight); ctx.SetSourceRGBA(69 / 255.0, 52 / 255.0, 36 / 255.0, 1); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.MainMenu) { // Top shine Rectangle(ctx, Bounds.bgDrawX, Bounds.bgDrawY, Bounds.OuterWidth, embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.Normal) { // Top shine Rectangle(ctx, Bounds.bgDrawX, Bounds.bgDrawY, Bounds.OuterWidth - embossHeight, embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); // Left shine Rectangle(ctx, Bounds.bgDrawX, Bounds.bgDrawY + embossHeight, embossHeight, Bounds.OuterHeight - embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); } // Pretty elaborate way of vertically centering the text. Le sigh. FontExtents fontex = normalText.Font.GetFontExtents(); TextExtents textex = normalText.Font.GetTextExtents(normalText.GetText()); double resetY = -fontex.Ascent - textex.YBearing; textOffsetY = resetY + (normalText.Bounds.InnerHeight + textex.YBearing) / 2; normalText.Bounds.fixedY += textOffsetY; normalText.ComposeElements(ctx, surface); normalText.Bounds.fixedY -= textOffsetY; // ShowMultilineText changes height Bounds.CalcWorldBounds(); if (buttonStyle == EnumButtonStyle.MainMenu) { // Bottom shade Rectangle(ctx, Bounds.bgDrawX, Bounds.bgDrawY + Bounds.OuterHeight - embossHeight, Bounds.OuterWidth, embossHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.Normal) { // Bottom shade Rectangle(ctx, Bounds.bgDrawX + embossHeight, Bounds.bgDrawY + Bounds.OuterHeight - embossHeight, Bounds.OuterWidth - 2 * embossHeight, embossHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); // Right shade Rectangle(ctx, Bounds.bgDrawX + Bounds.OuterWidth - embossHeight, Bounds.bgDrawY, embossHeight, Bounds.OuterHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.Normal) { //EmbossRoundRectangleElement(ctx, bounds.bgDrawX, bounds.bgDrawY, bounds.OuterWidth, bounds.OuterHeight, false, 2); } }
public void Paint() { if (Points == null) { ModifyBg(StateType.Normal, new Gdk.Color(0, 0, 0)); return; } Boundaries(Points, out float cXmin, out float cXmax, out float cYmin, out float cYmax); float ypad = Math.Abs((float.IsNaN(Ymax) ? cYmax : Ymax) - (float.IsNaN(Ymin) ? cYmin : Ymin)) * 0.15f; Xmin = (float.IsNaN(Xmin)) ? cXmin : Xmin; Xmax = (float.IsNaN(Xmax)) ? cXmax : Xmax; Ymin = (float.IsNaN(Ymin)) ? cYmin - ypad : Ymin; Ymax = (float.IsNaN(Ymax)) ? cYmax + ypad : Ymax; if (Xmin == Xmax) { Xmin -= 10; Xmax += 10; } if (Ymin == Ymax) { Ymin -= 10; Ymax += 10; } // Limit by x and y Point[] points = Array.FindAll(Points, p => p.X >= Xmin && p.X <= Xmax && p.Y >= Ymin && p.Y <= Ymax); Array.Sort(points); int paddingTop = 20; int paddingRight = 20; int paddingBottom = (XLabel != null) ? 60 : 20; int paddingLeft = (YLabel != null) ? 80 : 50; int width = Allocation.Width; int height = Allocation.Height; int xAxisWidth = width - paddingLeft - paddingRight; int yAxisHeight = height - paddingTop - paddingBottom; int xSpan = (int)Math.Abs(Xmax - Xmin); int ySpan = (int )Math.Abs(Ymax - Ymin); float xRatio = (float)xAxisWidth / xSpan; float yRatio = (float)yAxisHeight / ySpan; float xOrigo = paddingLeft - Xmin * xRatio; float yOrigo = paddingTop + Ymax * yRatio; int xTicks = xAxisWidth / PixelsPerTick; int yTicks = yAxisHeight / PixelsPerTick; Context cr = Gdk.CairoHelper.Create(this.GdkWindow); // Draw background cr.SetSourceColor(BckColor); cr.Rectangle(0, 0, width, height); cr.Fill(); // Draw bounding box cr.LineWidth = 2; cr.SetSourceColor(FrtColor); cr.Rectangle(paddingLeft, paddingTop, xAxisWidth, yAxisHeight); cr.Stroke(); // Draw x axis if (Ymin < 0 && Ymax > 0) { cr.LineWidth = 1; cr.SetSourceColor(AxisColor); cr.MoveTo(paddingLeft, yOrigo); cr.LineTo(paddingLeft + xAxisWidth, yOrigo); cr.Stroke(); } // Draw x ticks and values cr.SetSourceColor(FrtColor); cr.LineWidth = 2; List <Tick> xTicksList = CalculateTicks(Xmin, Xmax, xTicks); foreach (Tick tick in xTicksList) { float x = tick.Position * xRatio + xOrigo; cr.MoveTo(x, paddingTop + yAxisHeight - 5); cr.RelLineTo(0, 10); TextExtents te = cr.TextExtents(tick.Value); cr.RelMoveTo(-0.5 * te.Width, 10); cr.ShowText(tick.Value); } cr.Stroke(); // Draw x label if (XLabel != null) { cr.Save(); cr.SetFontSize(18); TextExtents te = cr.TextExtents(XLabel); cr.MoveTo(paddingLeft + xAxisWidth / 2 - te.Width / 2, height - te.Height); cr.ShowText(XLabel); cr.Restore(); } // Draw y axis if (Xmin < 0 && Xmax > 0) { cr.SetSourceColor(AxisColor); cr.MoveTo(xOrigo, paddingTop); cr.LineTo(xOrigo, paddingTop + yAxisHeight); cr.Stroke(); } // Draw y ticks and values cr.SetSourceColor(FrtColor); cr.LineWidth = 2; List <Tick> yTicksList = CalculateTicks(Ymin, Ymax, yTicks); foreach (Tick tick in yTicksList) { float y = yOrigo - tick.Position * yRatio; cr.MoveTo(paddingLeft - 5, y); cr.RelLineTo(10, 0); TextExtents te = cr.TextExtents(tick.Value); cr.RelMoveTo(-10 - te.Width - 5, 0.5 * te.Height); cr.ShowText(tick.Value); } cr.Stroke(); // Draw y label if (YLabel != null) { cr.Save(); cr.Translate(10, paddingTop + yAxisHeight / 2); cr.Rotate(-Math.PI / 2); cr.SetFontSize(18); TextExtents te = cr.TextExtents(YLabel); cr.MoveTo(-0.5 * te.Width, te.Height); cr.ShowText(YLabel); cr.Restore(); } cr.Translate(xOrigo, yOrigo); cr.SetSourceColor(FrtColor); switch (Type) { case PlotType.LinePlot: cr.LineWidth = 2; cr.MoveTo(points[0].X * xRatio, -points[0].Y * yRatio); for (int i = 1; i < points.Length; i++) { double xc = points[i].X * xRatio; double yc = -points[i].Y * yRatio; cr.LineTo(xc, yc); } cr.Stroke(); break; case PlotType.PointPlot: foreach (Point p in points) { double xc = p.X * xRatio; double yc = -p.Y * yRatio; cr.SetSourceColor(FrtColor); cr.MoveTo(xc, yc); cr.Arc(xc, yc, 2, 0, 2 * Math.PI); cr.Fill(); } break; case PlotType.PointLinePlot: cr.LineWidth = 2; cr.MoveTo(points[0].X * xRatio, -points[0].Y * yRatio); cr.Arc(points[0].X * xRatio, -points[0].Y * yRatio, 3, 0, 2 * Math.PI); cr.Fill(); cr.MoveTo(points[0].X * xRatio, -points[0].Y * yRatio); for (int i = 1; i < points.Length; i++) { double xc = points[i].X * xRatio; double yc = -points[i].Y * yRatio; cr.LineTo(xc, yc); cr.Stroke(); cr.Arc(xc, yc, 2, 0, 2 * Math.PI); cr.Fill(); cr.MoveTo(xc, yc); } break; } if (ShowCoordinates) { foreach (Point p in points) { double xc = p.X * xRatio; double yc = -p.Y * yRatio; cr.SetSourceRGB(1, 0, 0); cr.MoveTo(xc, yc); cr.ShowText(String.Format("{0}, {1}", p.X, p.Y)); } } // GC from example ((IDisposable)cr.GetTarget()).Dispose(); ((IDisposable)cr).Dispose(); }
private void UpdateViewSurface() { if (Constantes.escenario) { //whenever we want //draw onto our surface in memory using (Context cr = new Context(Constantes.viewSurface)) { if (ventana.circulo.Active) { if (!Constantes.contiene(Logica.circulos, new Obstaculo(xo, yo, Constantes.distancia(xt, xo), 0, (int)ventana.intermitencia.Value)) && Constantes.distancia(xt, xo) != 0) { Logica.circulos.Add(new Obstaculo(xo, yo, Constantes.distancia(xt, xo), 0, (int)ventana.intermitencia.Value)); } cr.LineWidth = 2; cr.SetSourceRGBA(0, 0, 1, 1); cr.Arc(xo, yo, Constantes.distancia(xt, xo), 0, Math.PI * 2); cr.Stroke(); } else if (ventana.linea.Active) { if (!Constantes.contiene(Logica.lineas, new Obstaculo(xo, yo, xt, yt, (int)ventana.intermitencia.Value)) && Constantes.distancia_dos_puntos(xo, yo, xt, yt) != 0) { Logica.lineas.Add(new Obstaculo(xo, yo, xt, yt, (int)ventana.intermitencia.Value)); } cr.LineWidth = 2; cr.SetSourceRGBA(0, 1, 0, 1); cr.MoveTo(xo, yo); cr.LineTo(xt, yt); cr.Stroke(); } else if (ventana.rectangulo.Active) { if (!Constantes.contiene(Logica.rectangulos, new Obstaculo(xo, yo, xt - xo, yt - yo, (int)ventana.intermitencia.Value)) && (Constantes.distancia(xt, xo) != 0 || Constantes.distancia(yt, yo) != 0)) { Logica.rectangulos.Add(new Obstaculo(xo, yo, xt - xo, yt - yo, (int)ventana.intermitencia.Value)); } cr.Rectangle(xo, yo, xt - xo, yt - yo); cr.LineWidth = 2; cr.SetSourceRGBA(1, 0, 0, 1); cr.Stroke(); } else if (ventana.puntoInicio.Active) { if (!Logica.puntos_inicio.Contains(new System.Drawing.Point(xo, yo))) { Logica.puntos_inicio.Add(new System.Drawing.Point(xo, yo)); } cr.SetSourceRGBA(1, 0, 1, 0.8); cr.Arc(xo, yo, 10, 0, 2 * Math.PI); cr.Fill(); cr.Stroke(); } else if (ventana.puntoObjetivo.Active) { int n = (int)ventana.nivel.Value; if (ventana.nivel.Value == Constantes.max_nivel) { Logica.puntos_objetivo.Add(new Objetivo()); Constantes.max_nivel++; ventana.nivel.SetRange(1, Constantes.max_nivel); } if (!Logica.puntos_objetivo [(int)ventana.nivel.Value - 1].contains(xo, yo)) { Logica.puntos_objetivo [(int)ventana.nivel.Value - 1].add_objetivo(xo, yo); } cr.SetSourceRGBA(1, 0, 0, 0.6); cr.Arc(xo, yo, Constantes.radio_objetivos, 0, 2 * Math.PI); cr.Fill(); cr.Stroke(); cr.SetSourceRGB(0, 0, 0); cr.SelectFontFace("Arial", FontSlant.Normal, FontWeight.Normal); cr.SetFontSize(12); TextExtents t = cr.TextExtents(n.ToString()); cr.MoveTo(xo - 4, yo + 4); cr.ShowText(n.ToString()); } cr.Dispose(); } } }
void Compose() { ComposeHover(true, ref leftHighlightTextureId); ComposeHover(false, ref rightHighlightTextureId); genOnTexture(); ImageSurface surface = new ImageSurface(Format.Argb32, Bounds.OuterWidthInt, Bounds.OuterHeightInt); Context ctx = new Context(surface); double rightBoxWidth = scaled(unscaledRightBoxWidth); Bounds.CalcWorldBounds(); var mod = (Mod)cell.Data; bool validMod = mod.Info != null; if (cell.DrawAsButton) { RoundRectangle(ctx, 0, 0, Bounds.OuterWidth, Bounds.OuterHeight, 0); ctx.SetSourceRGB(GuiStyle.DialogDefaultBgColor[0], GuiStyle.DialogDefaultBgColor[1], GuiStyle.DialogDefaultBgColor[2]); ctx.Fill(); } double textOffset = 0; if (validMod && mod.Icon != null) { int imageSize = (int)(Bounds.InnerHeight - Bounds.absPaddingY * 2 - 10); textOffset = imageSize + 10; Bitmap bmp = mod.Icon; surface.Image(bmp, (int)Bounds.absPaddingX + 5, (int)Bounds.absPaddingY + 5, imageSize, imageSize); bmp.Dispose(); } Font = cell.TitleFont; titleTextheight = textUtil.AutobreakAndDrawMultilineTextAt(ctx, Font, cell.Title, Bounds.absPaddingX + textOffset, Bounds.absPaddingY, Bounds.InnerWidth - textOffset); Font = cell.DetailTextFont; textUtil.AutobreakAndDrawMultilineTextAt(ctx, Font, cell.DetailText, Bounds.absPaddingX + textOffset, Bounds.absPaddingY + titleTextheight + Bounds.absPaddingY, Bounds.InnerWidth - textOffset); if (cell.RightTopText != null) { TextExtents extents = Font.GetTextExtents(cell.RightTopText); textUtil.AutobreakAndDrawMultilineTextAt(ctx, Font, cell.RightTopText, Bounds.absPaddingX + Bounds.InnerWidth - extents.Width - rightBoxWidth - scaled(10), Bounds.absPaddingY + scaled(cell.RightTopOffY), extents.Width + 1, EnumTextOrientation.Right); } if (cell.DrawAsButton) { EmbossRoundRectangleElement(ctx, 0, 0, Bounds.OuterWidth, Bounds.OuterHeight, false, 4, 0); } if (!validMod) { ctx.SetSourceRGBA(0, 0, 0, 0.5); RoundRectangle(ctx, 0, 0, Bounds.OuterWidth, Bounds.OuterHeight, 1); ctx.Fill(); } if (showModifyIcons) { double checkboxsize = scaled(unscaledSwitchSize); double padd = scaled(unscaledSwitchPadding); double x = Bounds.absPaddingX + Bounds.InnerWidth - scaled(0) - checkboxsize - padd; double y = Bounds.absPaddingY + Bounds.absPaddingY; ctx.SetSourceRGBA(0, 0, 0, 0.2); RoundRectangle(ctx, x, y, checkboxsize, checkboxsize, 3); ctx.Fill(); EmbossRoundRectangleElement(ctx, x, y, checkboxsize, checkboxsize, true, 1, 2); } generateTexture(surface, ref modcellTexture); ctx.Dispose(); surface.Dispose(); }
protected void CalculateSizesAndLoadFonts() { float windowHeight = this.Height; // Reserve part of the top screen space for the status text windowHeight *= 0.93f; playerSlotSize = this.Width / (double)playersPerSectionRow; playerSize = playerSlotSize * 0.9; playerSectionHeight = playerSlotSize * Math.Ceiling((double)Settings.Players / (double)playersPerSectionRow); playerSectionTop = this.Height - playerSectionHeight; foodSize = playerSize * 0.5; foodOffset = foodSize * 0.1; // Calculate plot layout plotAreaTop = this.Height - windowHeight; double plotAreaHeight = windowHeight - playerSectionHeight; double plotWidth = 0, plotHeight = 0, plotsPerRow = 0; switch (plots.Length) { case 4: case 10: plotsPerRow = 2; break; case 6: case 9: plotsPerRow = 3; break; case 8: plotsPerRow = 4; break; default: plotsPerRow = plots.Length; break; } plotWidth = this.Width / plotsPerRow; plotHeight = plotAreaHeight / ((double)plots.Length / plotsPerRow); // Load fonts float plotNumberFontSize = Math.Min(400.0f, (float)Math.Min(plotWidth, plotHeight) * 0.75f); plotNumberFont = new Font(FontFamily.GenericMonospace, plotNumberFontSize, FontStyle.Bold); plotNumberExtents = plotPrinter.Measure("0", plotNumberFont); // Set up plots for (int plotIndex = 0; plotIndex < plots.Length; plotIndex++) { plots[plotIndex] = new RectangleF( (float)((plotIndex % plotsPerRow) * plotWidth), (float)(plotAreaTop + ((plotIndex / (int)plotsPerRow) * plotHeight)), (float)plotWidth, (float)plotHeight ); plotNumberOffsets[plotIndex] = new PointF( (float)Math.Truncate((plotWidth - plotNumberExtents.BoundingBox.Width) / 2.0), (float)Math.Truncate((plotHeight - plotNumberExtents.BoundingBox.Height) / 2.0) ); } statusFont = new Font(FontFamily.GenericMonospace, (float)plotAreaTop * 0.55f, FontStyle.Bold); var statusExtents = statusPrinter.Measure("00:00", statusFont); statusTextPoint.X = (float)Math.Truncate((this.Width - statusExtents.BoundingBox.Width) / 2.0); statusTextPoint.Y = (float)Math.Truncate((plotAreaTop - statusExtents.BoundingBox.Height) / 2.0); scoreFont = new Font(FontFamily.GenericMonospace, (float)playerSlotSize * 0.5f, FontStyle.Bold); foodCountFont = new Font(FontFamily.GenericMonospace, (float)foodSize * 0.5f, FontStyle.Bold); }
void ComposeButton(Context ctx, ImageSurface surface) { double embossHeight = scaled(2.5); if (buttonStyle == EnumButtonStyle.Normal || buttonStyle == EnumButtonStyle.Small) { embossHeight = scaled(1.5); } if (buttonStyle != EnumButtonStyle.None) { // Brown background Rectangle(ctx, 0, 0, Bounds.OuterWidth, Bounds.OuterHeight); ctx.SetSourceRGBA(69 / 255.0, 52 / 255.0, 36 / 255.0, 1); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.MainMenu) { // Top shine Rectangle(ctx, 0, 0, Bounds.OuterWidth, embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.Normal || buttonStyle == EnumButtonStyle.Small) { // Top shine Rectangle(ctx, 0, 0, Bounds.OuterWidth - embossHeight, embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); // Left shine Rectangle(ctx, 0, 0 + embossHeight, embossHeight, Bounds.OuterHeight - embossHeight); ctx.SetSourceRGBA(1, 1, 1, 0.15); ctx.Fill(); } // Pretty elaborate way of vertically centering the text. Le sigh. FontExtents fontex = normalText.Font.GetFontExtents(); TextExtents textex = normalText.Font.GetTextExtents(normalText.GetText()); double resetY = -fontex.Ascent - textex.YBearing; textOffsetY = (resetY + (normalText.Bounds.InnerHeight + textex.YBearing) / 2) / RuntimeEnv.GUIScale; normalText.Bounds.fixedY += textOffsetY; normalText.ComposeElements(ctx, surface); normalText.Bounds.fixedY -= textOffsetY; // ShowMultilineText changes height Bounds.CalcWorldBounds(); if (buttonStyle == EnumButtonStyle.MainMenu) { // Bottom shade Rectangle(ctx, 0, 0 + Bounds.OuterHeight - embossHeight, Bounds.OuterWidth, embossHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); } if (buttonStyle == EnumButtonStyle.Normal || buttonStyle == EnumButtonStyle.Small) { // Bottom shade Rectangle(ctx, 0 + embossHeight, 0 + Bounds.OuterHeight - embossHeight, Bounds.OuterWidth - 2 * embossHeight, embossHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); // Right shade Rectangle(ctx, 0 + Bounds.OuterWidth - embossHeight, 0, embossHeight, Bounds.OuterHeight); ctx.SetSourceRGBA(0, 0, 0, 0.2); ctx.Fill(); } }
public Rectangle GetTextExtents(string text) { TextExtents extents = cr.TextExtents(text); return(new Rectangle((int)extents.XBearing, (int)extents.YBearing, (int)extents.Width, (int)extents.Height)); }
private void ComposeElement(GuiComposer composer, JsonDialogSettings settings, DialogElement elem, int elemKey, double x, double y) { double factor = settings.SizeMultiplier; double labelWidth = 0; if (elem.Label != null) { CairoFont font = CairoFont.WhiteSmallText(); font.UnscaledFontsize *= factor; TextExtents extents = font.GetTextExtents(elem.Label); labelWidth = extents.Width / factor / RuntimeEnv.GUIScale + 1; FontExtents fext = font.GetFontExtents(); ElementBounds labelBounds = ElementBounds.Fixed(x, y + Math.Max(0, (elem.Height * factor - fext.Height / RuntimeEnv.GUIScale) / 2), labelWidth, elem.Height).WithScale(factor); composer.AddStaticText(elem.Label, font, labelBounds); labelWidth += 8; if (elem.Tooltip != null) { CairoFont tfont = CairoFont.WhiteSmallText(); tfont.UnscaledFontsize *= factor; composer.AddHoverText(elem.Tooltip, tfont, 350, labelBounds.FlatCopy(), "tooltip-" + elem.Code); composer.GetHoverText("tooltip-" + elem.Code).SetAutoWidth(true); } } ElementBounds bounds = ElementBounds.Fixed(x + labelWidth, y, elem.Width - labelWidth, elem.Height).WithScale(factor); string currentValue = settings.OnGet?.Invoke(elem.Code); switch (elem.Type) { case EnumDialogElementType.Slider: { string key = "slider-" + elemKey; composer.AddSlider((newval) => { settings.OnSet?.Invoke(elem.Code, newval + ""); return(true); }, bounds, key); int curVal = 0; int.TryParse(currentValue, out curVal); composer.GetSlider(key).SetValues(curVal, elem.MinValue, elem.MaxValue, elem.Step); composer.GetSlider(key).Scale = factor; //composer.GetSlider(key).TriggerOnlyOnMouseUp(true); break; } case EnumDialogElementType.Switch: { string key = "switch-" + elemKey; composer.AddSwitch((newval) => { settings.OnSet?.Invoke(elem.Code, newval ? "1" : "0"); }, bounds, key, 30 * factor, 5 * factor); composer.GetSwitch(key).SetValue(currentValue == "1"); } break; case EnumDialogElementType.Input: { string key = "input-" + elemKey; CairoFont font = CairoFont.WhiteSmallText(); font.UnscaledFontsize *= factor; composer.AddTextInput(bounds, (newval) => { settings.OnSet?.Invoke(elem.Code, newval); }, font, key); composer.GetTextInput(key).SetValue(currentValue); break; } case EnumDialogElementType.NumberInput: { string key = "numberinput-" + elemKey; CairoFont font = CairoFont.WhiteSmallText(); font.UnscaledFontsize *= factor; composer.AddNumberInput(bounds, (newval) => { settings.OnSet?.Invoke(elem.Code, newval); }, font, key); composer.GetNumberInput(key).SetValue(currentValue); break; } case EnumDialogElementType.Button: if (elem.Icon != null) { composer.AddIconButton(elem.Icon, (val) => { settings.OnSet?.Invoke(elem.Code, null); }, bounds); } else { CairoFont font = CairoFont.ButtonText(); font.WithFontSize(elem.FontSize); composer.AddButton(elem.Text, () => { settings.OnSet?.Invoke(elem.Code, null); return(true); }, bounds.WithFixedPadding(8, 0), font); } if (elem.Tooltip != null && elem.Label == null) { CairoFont tfont = CairoFont.WhiteSmallText(); tfont.UnscaledFontsize *= factor; composer.AddHoverText(elem.Tooltip, tfont, 350, bounds.FlatCopy(), "tooltip-" + elem.Code); composer.GetHoverText("tooltip-" + elem.Code).SetAutoWidth(true); } break; case EnumDialogElementType.Text: composer.AddStaticText(elem.Text, CairoFont.WhiteMediumText().WithFontSize(elem.FontSize), bounds); break; case EnumDialogElementType.Select: case EnumDialogElementType.DynamicSelect: { string[] values = elem.Values; string[] names = elem.Names; if (elem.Type == EnumDialogElementType.DynamicSelect) { string[] compos = currentValue.Split(new string[] { "\n" }, StringSplitOptions.None); values = compos[0].Split(new string[] { "||" }, StringSplitOptions.None); names = compos[1].Split(new string[] { "||" }, StringSplitOptions.None); currentValue = compos[2]; } int selectedIndex = Array.FindIndex(values, w => w.Equals(currentValue)); if (elem.Mode == EnumDialogElementMode.DropDown) { string key = "dropdown-" + elemKey; composer.AddDropDown(values, names, selectedIndex, (newval, on) => { settings.OnSet?.Invoke(elem.Code, newval); }, bounds, key); composer.GetDropDown(key).Scale = factor; composer.GetDropDown(key).Font.UnscaledFontsize *= factor; } else { if (elem.Icons != null && elem.Icons.Length > 0) { ElementBounds[] manybounds = new ElementBounds[elem.Icons.Length]; double elemHeight = (elem.Height - 4 * elem.Icons.Length) / elem.Icons.Length; for (int i = 0; i < manybounds.Length; i++) { manybounds[i] = bounds.FlatCopy().WithFixedHeight(elemHeight - 4).WithFixedOffset(0, i * (4 + elemHeight)).WithScale(factor); } string key = "togglebuttons-" + elemKey; CairoFont font = CairoFont.WhiteSmallText(); font.UnscaledFontsize *= factor; composer.AddIconToggleButtons(elem.Icons, font, (newval) => { settings.OnSet?.Invoke(elem.Code, elem.Values[newval]); }, manybounds, key); if (currentValue != null && currentValue.Length > 0) { composer.ToggleButtonsSetValue(key, selectedIndex); } if (elem.Tooltips != null) { for (int i = 0; i < elem.Tooltips.Length; i++) { CairoFont tfont = CairoFont.WhiteSmallText(); tfont.UnscaledFontsize *= factor; composer.AddHoverText(elem.Tooltips[i], tfont, 350, manybounds[i].FlatCopy()); } } } } } break; } elementNumber++; }