internal static bool TryFormatUInt64(ulong value, byte numberOfBytes, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
        {
            if(format.Symbol == 'g')
            {
                format.Symbol = 'G';
            }

            if (format.IsHexadecimal && formattingData.IsInvariantUtf16) {
                return TryFormatHexadecimalInvariantCultureUtf16(value, buffer, format, out bytesWritten);
            }

            if (format.IsHexadecimal && formattingData.IsInvariantUtf8) {
                return TryFormatHexadecimalInvariantCultureUtf8(value, buffer, format, out bytesWritten);
            }

            if ((formattingData.IsInvariantUtf16) && (format.Symbol == 'D' || format.Symbol == 'G')) {
                return TryFormatDecimalInvariantCultureUtf16(value, buffer, format, out bytesWritten);
            }

            if ((formattingData.IsInvariantUtf8) && (format.Symbol == 'D' || format.Symbol == 'G')) {
                return TryFormatDecimalInvariantCultureUtf8(value, buffer, format, out bytesWritten);
            }

            return TryFormatDecimal(value, buffer, format, formattingData, out bytesWritten);     
        }
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);

            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola",
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                72);

            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;

            float width = ClientSize.Width / _dpiScaleX;
            float height = ClientSize.Height / _dpiScaleY;

            this._textLayout = DirectWriteFactory.CreateTextLayout(
                _text,
                this._textFormat,
                width,
                height);

            using (Typography typography = DirectWriteFactory.CreateTypography())
            {
                typography.AddFontFeature(FontFeatureTag.StylisticSet7, 1);
                this._textLayout.SetTypography(typography, new TextRange(0, _text.Length));
            }

            Bitmap bitmap = RenderTarget.CreateBitmap(this.GetType(), "heart.png");

            this._bitmapInlineObject = new BitmapInlineObject(RenderTarget, bitmap);

            this._textLayout.SetInlineObject(this._bitmapInlineObject, new TextRange(2, 1));
        }
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);

            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola",
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                72);

            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;

            float width = ClientSize.Width / _dpiScaleX;
            float height = ClientSize.Height / _dpiScaleY;

            this._textLayout = DirectWriteFactory.CreateTextLayout(
                _text,
                this._textFormat,
                width,
                height);

            this._textLayout.SetFontSize(100, new TextRange(20, 6));
            this._textLayout.SetUnderline(true, new TextRange(20, 11));
            this._textLayout.SetFontWeight(FontWeight.Bold, new TextRange(20, 11));

            using (Typography typography = DirectWriteFactory.CreateTypography())
            {
                typography.AddFontFeature(FontFeatureTag.StylisticSet7, 1);
                this._textLayout.SetTypography(typography, new TextRange(0, _text.Length));
            }
        }
示例#4
0
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);
            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola", 72);
            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            float width = ClientSize.Width / dpiScaleX;
            float height = ClientSize.Height / dpiScaleY;
            this._textLayout = DirectWriteFactory.CreateTextLayout("Click on this text Click on this text", this._textFormat, width, height);
            this._textAnalyzer = DirectWriteFactory.CreateTextAnalyzer();
            this._source = new MyTextSource("Click on this text Click on this text");
            using (FontCollection coll = this._textFormat.FontCollection)
            {
                int count = coll.Count;
                for (int index = 0; index < count; ++index)
                {
                    using (FontFamily ff = coll[index])
                    {
                        using (Font font = ff.GetFirstMatchingFont(FontWeight.Normal, FontStretch.Normal, FontStyle.Normal))
                        {
                            LocalizedStrings ls = font.FaceNames;
                            LocalizedStrings desc = font.GetInformationalStrings(InformationalStringId.Designer);

                            int cultureIndex = ls.FindCulture(CultureInfo.CurrentCulture);
                            string faceName = ls[cultureIndex];
                            FontMetrics metrics = font.Metrics;
                        }
                    }
                }
            }
            this._textAnalyzer.AnalyzeLineBreakpoints(_source, 0, (uint)_source.Text.Length);
            this._textAnalyzer.AnalyzeScript(_source, 0, (uint)_source.Text.Length);
        }
示例#5
0
 protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
 {
     base.OnCreateDeviceIndependentResources(factory);
     this._textFormat = DirectWriteFactory.CreateTextFormat("Verdana", FontWeight.Bold, FontStyle.Normal, FontStretch.Normal, 10.5f);
     this._textFormat.ParagraphAlignment = ParagraphAlignment.Near;
     this._textFormat.TextAlignment = TextAlignment.Center;
 }
示例#6
0
	void Start ( ) {
		
		BMFontReader.registerFonts( bmFonts );
		
		// Font linkage from swf using font name & size mapping
		stage.addChild( new MovieClip("uniSWF/Examples/Extra examples/BMFont reader/swf/bmfonttest.swf:Font") );
		
		
		// Add Text to stage
		TextFormat format = new TextFormat();
		format.font = "Times Bold";
		format.color = Color.green;
		format.size = 64;
		BitmapTextField txt = new BitmapTextField( );
		txt.width = 500;
		txt.height = 200;
		txt.textFormat = format;		
		txt.text = "BMText set from code";
		txt.y = 100;
		txt.x = 10;
		
		txt.type = TextFieldType.INPUT;
		
		txt.addCharColor( 7, 9, Color.cyan );
		txt.addCharColor( 16, 19, Color.red );
		
		txt.appendText( ", Appended text" );
		stage.addChild( txt );
		
		
	}
        public static bool TryFormat(this DateTime value, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');

            switch (format.Symbol)
            {
                case 'R':
                    var utc = value.ToUniversalTime();
                    if (formattingData.IsInvariantUtf16)
                    {
                        return TryFormatDateTimeRfc1123(utc, buffer, EncodingData.InvariantUtf16, out bytesWritten);
                    }
                    else
                    {
                        return TryFormatDateTimeRfc1123(utc, buffer, EncodingData.InvariantUtf8, out bytesWritten);
                    }
                case 'O':
                    if (formattingData.IsInvariantUtf16)
                    {
                        return TryFormatDateTimeFormatO(value, true, buffer, EncodingData.InvariantUtf16, out bytesWritten);
                    }
                    else
                    {
                        return TryFormatDateTimeFormatO(value, true, buffer, EncodingData.InvariantUtf8, out bytesWritten);
                    }
                case 'G':
                    return TryFormatDateTimeFormagG(value, buffer, formattingData, out bytesWritten);
                default:
                    throw new NotImplementedException();
            }      
        }
示例#8
0
文件: Button.cs 项目: crl/UniStarling
        public Button(DisplayObject upState, string text ="", DisplayObject downState=null, TextFormat format=null)
        {
            //if (upState == null) throw new ErrorEvent("Texture cannot be null");

            mParent = upState.parent;
            mUpState = upState;
            mDownState = downState != null ? downState : upState;
            mBackground = upState;
            mTextFormat = format;

            mScaleWhenDown = 0.9f;
            mAlphaWhenDisabled = 0.5f;
            mEnabled = true;
            mIsDown = false;
            mUseHandCursor = true;
            mTextBounds = new Rectangle(0, 0, upState.width, upState.height);

            mContents = new Sprite();
            mContents.addChild(mBackground);
            addChild(mContents);

            //addEventListener(TouchEvent.TOUCH, onTouch);
            addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);

            if (text.Length > 0) this.text = text;

            this.x = upState.x;
            this.y = upState.y;
            upState.x = upState.y = 0;

            if(mParent != null)
                (mParent as MovieClip).addChild(this);
        }
        public static bool TryFormat(this DateTimeOffset value, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');
            switch (format.Symbol)
            {
                case 'R':

                    if (formattingData.IsInvariantUtf16) // TODO: there are many checks like this one in the code. They need to also verify that the UTF8 branch is invariant.
                    {
                        return TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, EncodingData.InvariantUtf16, out bytesWritten);
                    }
                    else
                    {
                        return TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, EncodingData.InvariantUtf8, out bytesWritten);
                    }
                case 'O':
                    if (formattingData.IsInvariantUtf16)
                    {
                        return TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, EncodingData.InvariantUtf16, out bytesWritten);
                    }
                    else
                    {
                        return TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, EncodingData.InvariantUtf8, out bytesWritten);
                    }
                case 'G':
                    return TryFormatDateTimeFormagG(value.DateTime, buffer, formattingData, out bytesWritten);
                default:
                    throw new NotImplementedException();
            }
        }
示例#10
0
        internal static bool TryFormatInt64(long value, byte numberOfBytes, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
        {
            Precondition.Require(numberOfBytes <= sizeof(long));

            if (value >= 0)
            {
                return TryFormatUInt64(unchecked((ulong)value), numberOfBytes, buffer, format, formattingData, out bytesWritten);
            }
            else if (format.IsHexadecimal)
            {
                ulong bitMask = GetBitMask(numberOfBytes);
                return TryFormatUInt64(unchecked((ulong)value) & bitMask, numberOfBytes, buffer, format, formattingData, out bytesWritten);
            }
            else
            {
                int minusSignBytes = 0;
                if(!formattingData.TryEncode(EncodingData.Symbol.MinusSign, buffer, out minusSignBytes))
                {
                    bytesWritten = 0;
                    return false;
                }

                int digitBytes = 0;
                if(!TryFormatUInt64(unchecked((ulong)-value), numberOfBytes, buffer.Slice(minusSignBytes), format, formattingData, out digitBytes))
                {
                    bytesWritten = 0;
                    return false;
                }
                bytesWritten = digitBytes + minusSignBytes;
                return true;
            }
        }
示例#11
0
 private void CreateTextFormat()
 {
     var factory = new SlimDX.DirectWrite.Factory(SlimDX.DirectWrite.FactoryType.Shared);
     mTextFormat = factory.CreateTextFormat("Consola", FontWeight.Normal,
         SlimDX.DirectWrite.FontStyle.Normal, FontStretch.Normal, 100, "en-us");
     mTextFormat.TextAlignment = TextAlignment.Center;
     mTextFormat.ParagraphAlignment = ParagraphAlignment.Center;
 }
示例#12
0
 public ScenarioBuilder When(
     string stepName, 
     Action<Step> action = null, 
     string multilineParameter = "",
     TextFormat multilineParameterFormat = TextFormat.text)
 {
     var step = factory.CreateStep(stepName, action, multilineParameter, multilineParameterFormat);
     return When(step);
 }
示例#13
0
 public static Step CreateStep(
     string stepName, 
     Action<Step> action = null, 
     string multilineParameter = "",
     TextFormat multilineParameterFormat = TextFormat.text)
 {
     action = action ?? ((s) => { });
     return factory.CreateStep(stepName, action, multilineParameter, multilineParameterFormat);
 }
示例#14
0
 public static Step CreateAsyncStep(
     string stepName, 
     Func<Step, Task> action = null,
     string multilineParameter = "",
     TextFormat multilineParameterFormat = TextFormat.text)
 {
     action = action ?? ((s) => { return Task.Run(() => { }); });
     return factory.CreateStep(stepName, action, multilineParameter, multilineParameterFormat);
 }
 public static bool TryFormat(this float value, Span<byte> buffer, TextFormat format, EncodingData formattingData, out int bytesWritten)
 {
     if (format.IsDefault)
     {
         format.Symbol = 'G';
     }
     Precondition.Require(format.Symbol == 'G');
     return FloatFormatter.TryFormatNumber(value, true, buffer, format, formattingData, out bytesWritten);
 }
示例#16
0
 public ScenarioBuilder GivenAsync(
     string stepName, 
     Func<Step, Task> action = null, 
     string multilineParameter = "",
     TextFormat multilineParameterFormat = TextFormat.text)
 {
     var step = factory.CreateStep(stepName, action, multilineParameter, multilineParameterFormat);
     return Given(step);
 }
示例#17
0
        public void DrawString(string text, Rectangle rectangle, TextFormat format, Color4 color)
        {
            QFont.Begin();

            _font.Options.Colour = color.ToGLColor4();
            _font.Print(text, new OpenTK.Vector2(rectangle.X, rectangle.Y));

            QFont.End();
        }
示例#18
0
 protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
 {
     base.OnCreateDeviceIndependentResources(factory);
     this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola", 72);
     this._textFormat.TextAlignment = TextAlignment.Center;
     this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;
     float width = ClientSize.Width / dpiScaleX;
     float height = ClientSize.Height / dpiScaleY;
     this._textLayout = DirectWriteFactory.CreateTextLayout("Click on this text", this._textFormat, width, height);
 }
示例#19
0
 internal Step CreateStep(string stepName, Func<Step, Task> action, string multilineParameter, TextFormat multilineParameterFormat)
 {
     return new Step()
     {
         Name = stepName,
         ActionAsync = action,
         MultilineParameter = multilineParameter,
         MultilineParameterFormat = multilineParameterFormat
     };
 }
        public bool TryFormat(Span<byte> buffer, out int bytesWritten, TextFormat format, EncodingData encoding)
        {
            if (!PrimitiveFormatter.TryFormat(_age, buffer, out bytesWritten, format, encoding)) return false;


            char symbol = _inMonths ? 'm' : 'y';
            int symbolBytes;
            if (!PrimitiveFormatter.TryEncode(symbol, buffer.Slice(bytesWritten), out symbolBytes, encoding.TextEncoding)) return false;

            bytesWritten += symbolBytes;
            return true;
        }
示例#21
0
 internal static List<Point> GetInputData(string file, TextFormat fmt)
 {
     if (fmt == TextFormat.csv)
     {
     return GetCsvData(file);
     }
     if (fmt == TextFormat.vic)
     {
     return GetVicData(file);
     }
     return new List<Point> { };
 }
示例#22
0
文件: Font.cs 项目: HaKDMoDz/Psy
 /// <summary>
 /// Measures width of string, correctly taking into account trailing spaces.
 /// </summary>
 /// <param name="text"></param>
 /// <param name="textFormat"></param>
 /// <returns></returns>
 public Rectangle MeasureString(string text, TextFormat textFormat)
 {
     if (_spaceWidth == -1)
     {
         CalculateSpaceWidth();
     }
     var size = MeasureString(null, text, MapTextFormat(textFormat));
     var trimStr = text.TrimEnd(' ');
     var spaceCount = text.Length - trimStr.Length;
     size.Width += (_spaceWidth * spaceCount);
     return size;
 }
示例#23
0
        public ProgressUpdate(WindowRenderTarget rt1) {
            _rt = rt1;
            _brush = new SolidColorBrush(_rt, Color.Green);
            _clearColor = new SolidColorBrush(_rt, Color.Black);

            _borderBounds = new Rectangle(18, rt1.PixelSize.Height / 2 - 2, rt1.PixelSize.Width - 36, 24);
            _barBounds = new Rectangle(20, rt1.PixelSize.Height / 2, rt1.PixelSize.Width - 40, 20);

            _factory = new Factory(FactoryType.Isolated);
            _txtFormat = new TextFormat(_factory, "Arial", FontWeight.Normal, FontStyle.Normal, FontStretch.Normal, 18, "en-us") {
                TextAlignment = TextAlignment.Center
            };
            _textRect = new Rectangle(100, rt1.PixelSize.Height / 2 - 25, _rt.PixelSize.Width - 200, 20);
        }
示例#24
0
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);
            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola",
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                72);
            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;

            System.Globalization.CultureInfo ci = this._textFormat.Culture;
            Trimming trimming = this._textFormat.Trimming;
        }
示例#25
0
	void Start ( ) {
		
		// 
		// Alter existing font
		
		// Add root with single textfield
		mc = new MovieClip( "uniSWF/Examples/Extra examples/ProgramaticTextFields/swf/programaticText.swf:Root" ) ;
		stage.addChild( mc );
		
		// Ensure player is not changing textfields on timeline
		mc.stop();
		
		 // Get textfield
		txt = mc.getChildByName<TextField>( "txt" );
		
		// Get format
		TextFormat format = txt.textFormat;
		
		// Set new format
		format.fontClassName = null;	// Clear class for bitmap fonts as this points to the exact font_size_filters assets
		format.size = 30;
		
		// Set format
		txt.textFormat = format;
		
		
		
		//
		// Add new textfield using font and size ( must be exported )		
		format = new TextFormat();
		format.font = "Times Bold";
		format.color = Color.green;
		format.size = 64;
		BitmapTextField bmpTxt = new BitmapTextField( );
		bmpTxt.width = 500;
		bmpTxt.height = 200;
		bmpTxt.textFormat = format;		
		bmpTxt.text = "Text set from code";
		bmpTxt.y = 100;
		bmpTxt.x = 10;
		
		bmpTxt.type = TextFieldType.INPUT;
		
		bmpTxt.addCharColor( 5, 8, Color.cyan );
		bmpTxt.addCharColor( 14, 17, Color.red );
		
		bmpTxt.appendText( ", Appended text" );
		stage.addChild( bmpTxt );		
	}
示例#26
0
        internal static List<Point> DoBiasCorrection(string observedFile,
            string baselineFile, string futureFile, TextFormat infmt)
        {
            //get input data
            List<Point> observed = GetInputData(observedFile, infmt);
            List<Point> baseline = GetInputData(baselineFile, infmt);
            List<Point> future = GetInputData(futureFile, infmt);
            if (observed.Count == 0 || baseline.Count == 0 || future.Count == 0)
            {
            Console.WriteLine("error parsing input file(s)");
            return new List<Point> { };
            }

            //get monthly data
            List<Point> observedMonthly = DataToMonthly(observed);
            List<Point> baselineMonthly = DataToMonthly(baseline);
            List<Point> futureMonthly = DataToMonthly(future);
            if (observedMonthly.Count == 0 || baselineMonthly.Count == 0
                || futureMonthly.Count == 0)
            {
            Console.WriteLine("error parsing input file(s) to monthly");
            return new List<Point> { };
            }

            //truncate inputs to water year data
            Utils.TruncateToWYs(observedMonthly);
            Utils.TruncateToWYs(baselineMonthly);
            Utils.TruncateToWYs(futureMonthly);
            Utils.TruncateToWYs(future);

            //align baseline and observed records for proper quantile lookup
            Utils.AlignPeriods(observedMonthly, baselineMonthly);

            //do monthly bias correction
            List<Point> biasedMonthly = DoMonthlyBiasCorrection(observedMonthly,
                                    baselineMonthly, futureMonthly);
            List<Point> biasedFinal = DoAnnualBiasCorrection(observedMonthly,
                                  baselineMonthly, futureMonthly, biasedMonthly);

            //do daily adjustments
            if (Utils.IsDataDaily(future))
            {
            List<Point> biasedDaily = AdjDailyToMonthly(future, biasedFinal);
            AdjMonthlyBoundary(biasedDaily);
            biasedFinal = AdjDailyToMonthly(biasedDaily, biasedFinal);
            }

            return biasedFinal;
        }
        public static FormattedText Format(this FormattedText formattedText, TextFormat textFormat)
        {
            if (formattedText == null)
            {
                throw new ArgumentNullException("formattedText");
            }

            Action<FormattedText> formatter;
            if (formats.TryGetValue(textFormat, out formatter))
            {
                formatter(formattedText);
            }

            return formattedText;
        }
示例#28
0
        private static bool TryFormatDecimalInvariantCultureUtf16(ulong value, Span<byte> buffer, TextFormat format, out int bytesWritten)
        {
            Precondition.Require(format.Symbol == 'D' || format.Symbol == 'G');

            // Count digits
            var valueToCountDigits = value;
            var digitsCount = 1;
            while (valueToCountDigits >= 10UL) {
                valueToCountDigits = valueToCountDigits / 10UL;
                digitsCount++;
            }

            var index = 0;
            var bytesCount = digitsCount * 2;

            // If format is D and precision is greater than digits count, append leading zeros
            if (format.Symbol == 'D' && format.HasPrecision) {
                var leadingZerosCount = format.Precision - digitsCount;
                if (leadingZerosCount > 0) {
                    bytesCount += leadingZerosCount * 2;
                }

                if (bytesCount > buffer.Length) {
                    bytesWritten = 0;
                    return false;
                }

                while (leadingZerosCount-- > 0) {
                    buffer[index++] = (byte)'0';
                    buffer[index++] = 0;
                }
            }
            else if (bytesCount > buffer.Length) {
                bytesWritten = 0;
                return false;
            }

            index = bytesCount;
            while (digitsCount-- > 0) {
                ulong digit = value % 10UL;
                value /= 10UL;
                buffer[--index] = 0;
                buffer[--index] = (byte)(digit + (ulong)'0'); 
            }

            bytesWritten = bytesCount;
            return true;
        }
        protected override void OnRefresh()
        {
            ScreenReplicator replicator = Visual as ScreenReplicator;
            _inactiveBrush = Brushes.Yellow;
            _inactivePen = new Pen(_inactiveBrush, 1d);
            _inactivePen.DashStyle = DashStyles.Dash;
            _inactiveTextFormat = new TextFormat();
            _inactiveTextFormat.VerticalAlignment = TextVerticalAlignment.Center;
            _inactiveTextFormat.VerticalAlignment = TextVerticalAlignment.Center;

            if (replicator != null)
            {
                _displayRect.Width = replicator.Width;
                _displayRect.Height = replicator.Height;
            }
        }
示例#30
0
文件: Font.cs 项目: HaKDMoDz/Psy
        private static DrawTextFormat MapTextFormat(TextFormat format)
        {
            var drawTextFormat = DrawTextFormat.Top;

            if (format.HasFlag(TextFormat.Bottom))
            {
                drawTextFormat ^= DrawTextFormat.Bottom;
            }

            if (format.HasFlag(TextFormat.Center))
            {
                drawTextFormat ^= DrawTextFormat.Center;
            }

            if (format.HasFlag(TextFormat.Left))
            {
                drawTextFormat ^= DrawTextFormat.Left;
            }

            if (format.HasFlag(TextFormat.Right))
            {
                drawTextFormat ^= DrawTextFormat.Right;
            }

            if (format.HasFlag(TextFormat.SingleLine))
            {
                drawTextFormat ^= DrawTextFormat.SingleLine;
            }

            if (format.HasFlag(TextFormat.Top))
            {
                drawTextFormat ^= DrawTextFormat.Top;
            }

            if (format.HasFlag(TextFormat.WordBreak))
            {
                drawTextFormat ^= DrawTextFormat.WordBreak;
            }

            if (format.HasFlag(TextFormat.VerticalCenter))
            {
                drawTextFormat ^= DrawTextFormat.VerticalCenter;
            }

            return drawTextFormat;
        }
示例#31
0
 public void OnUpdateTarget(Factory factory)
 {
     mFormat = new TextFormat(factory, Family, Weight, mStyle, Size);
 }
示例#32
0
 public string GetSelectedText(ref TextFormat format)
 {
     format = TextFormat.Html;
     return(Core.WebBrowser.SelectedHtml);
 }
 public CSGOControl(CSGOTheme theme, TextFormat font)
     : this(theme, font, 0f, 0f)
 {
 }
示例#34
0
 public override string ToString()
 {
     return(TextFormat.ShortDebugString(GetProto()));
 }
 public Radar(CSGOTheme theme, TextFormat font)
     : this(theme, font, 10f)
 {
 }
示例#36
0
        // String is positioned relative to x,y according to TextFormat.
        // TextFormat also controls text alignment (left, center, right).
        // Handles embedded newlines.
        public static void DrawString(AbstractGraphics g, string text, Font font, AbstractBrush brush, float x, float y, TextFormat format = TextFormat.Center)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            var lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).ToList();
            var sizes = lines.Select(s => g.MeasureString(s, font)).ToList();

            float fontUnitsToWorldUnits = font.Size / font.FontFamily.GetEmHeight(font.Style);
            float lineSpacing           = font.FontFamily.GetLineSpacing(font.Style) * fontUnitsToWorldUnits;
            float ascent  = font.FontFamily.GetCellAscent(font.Style) * fontUnitsToWorldUnits;
            float descent = font.FontFamily.GetCellDescent(font.Style) * fontUnitsToWorldUnits;

            SizeF boundingSize = new SizeF(sizes.Max(s => s.Width), lineSpacing * sizes.Count());

            // Offset from baseline to top-left.
            y += ascent;

            float widthFactor = 0;

            switch (format)
            {
            case TextFormat.MiddleLeft:
            case TextFormat.Center:
            case TextFormat.MiddleRight:
                y -= boundingSize.Height / 2;
                break;

            case TextFormat.BottomLeft:
            case TextFormat.BottomCenter:
            case TextFormat.BottomRight:
                y -= boundingSize.Height;
                break;
            }
            switch (format)
            {
            case TextFormat.TopCenter:
            case TextFormat.Center:
            case TextFormat.BottomCenter:
                widthFactor = -0.5f;
                break;

            case TextFormat.TopRight:
            case TextFormat.MiddleRight:
            case TextFormat.BottomRight:
                widthFactor = -1;
                break;
            }

            Util.ForEachZip(lines, sizes, (line, sz) =>
            {
                g.DrawString(line, font, brush, x + widthFactor * sz.Width, y, StringAlignment.Baseline);
                y += lineSpacing;
            });
        }
示例#37
0
        virtual public void Parse(string aSource, TextFormat defaultFormat, List <HtmlElement> elements, HtmlParseOptions parseOptions)
        {
            if (parseOptions == null)
            {
                parseOptions = _defaultOptions;
            }

            _elements           = elements;
            _textFormatStackTop = 0;
            _format.CopyFrom(defaultFormat);
            _format.colorChanged = false;
            int    skipText         = 0;
            bool   ignoreWhiteSpace = parseOptions.ignoreWhiteSpace;
            bool   skipNextCR       = false;
            string text;

            XMLIterator.Begin(aSource, true);
            while (XMLIterator.NextTag())
            {
                if (skipText == 0)
                {
                    text = XMLIterator.GetText(ignoreWhiteSpace);
                    if (text.Length > 0)
                    {
                        if (skipNextCR && text[0] == '\n')
                        {
                            text = text.Substring(1);
                        }
                        AppendText(text);
                    }
                }

                skipNextCR = false;
                switch (XMLIterator.tagName)
                {
                case "b":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.bold = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "i":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.italic = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "u":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.underline = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "strike":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.strikethrough = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "sub":
                {
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.specialStyle = TextFormat.SpecialStyle.Subscript;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                }
                break;

                case "sup":
                {
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.specialStyle = TextFormat.SpecialStyle.Superscript;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                }
                break;

                case "font":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();

                        _format.size = XMLIterator.GetAttributeInt("size", _format.size);
                        string color = XMLIterator.GetAttribute("color");
                        if (color != null)
                        {
                            string[] parts = color.Split(',');
                            if (parts.Length == 1)
                            {
                                _format.color         = ToolSet.ConvertFromHtmlColor(color);
                                _format.gradientColor = null;
                                _format.colorChanged  = true;
                            }
                            else
                            {
                                if (_format.gradientColor == null)
                                {
                                    _format.gradientColor = new Color32[4];
                                }
                                _format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]);
                                _format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]);
                                if (parts.Length > 2)
                                {
                                    _format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]);
                                    if (parts.Length > 3)
                                    {
                                        _format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]);
                                    }
                                    else
                                    {
                                        _format.gradientColor[3] = _format.gradientColor[2];
                                    }
                                }
                                else
                                {
                                    _format.gradientColor[2] = _format.gradientColor[0];
                                    _format.gradientColor[3] = _format.gradientColor[1];
                                }
                            }
                        }
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        PopTextFormat();
                    }
                    break;

                case "br":
                    AppendText("\n");
                    break;

                case "img":
                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                    {
                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image);
                        element.FetchAttributes();
                        element.name         = element.GetString("name");
                        element.format.align = _format.align;
                        _elements.Add(element);
                    }
                    break;

                case "a":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();

                        _format.underline = _format.underline || parseOptions.linkUnderline;
                        if (!_format.colorChanged && parseOptions.linkColor.a != 0)
                        {
                            _format.color = parseOptions.linkColor;
                        }

                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link);
                        element.FetchAttributes();
                        element.name         = element.GetString("name");
                        element.format.align = _format.align;
                        _elements.Add(element);
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        PopTextFormat();

                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd);
                        _elements.Add(element);
                    }
                    break;

                case "input":
                {
                    HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input);
                    element.FetchAttributes();
                    element.name = element.GetString("name");
                    element.format.CopyFrom(_format);
                    _elements.Add(element);
                }
                break;

                case "select":
                {
                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                    {
                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select);
                        element.FetchAttributes();
                        if (XMLIterator.tagType == XMLTagType.Start)
                        {
                            sHelperList1.Clear();
                            sHelperList2.Clear();
                            while (XMLIterator.NextTag())
                            {
                                if (XMLIterator.tagName == "select")
                                {
                                    break;
                                }

                                if (XMLIterator.tagName == "option")
                                {
                                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                                    {
                                        sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty));
                                    }
                                    else
                                    {
                                        sHelperList1.Add(XMLIterator.GetText());
                                    }
                                }
                            }
                            element.Set("items", sHelperList1.ToArray());
                            element.Set("values", sHelperList2.ToArray());
                        }
                        element.name = element.GetString("name");
                        element.format.CopyFrom(_format);
                        _elements.Add(element);
                    }
                }
                break;

                case "p":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        string align = XMLIterator.GetAttribute("align");
                        switch (align)
                        {
                        case "center":
                            _format.align = AlignType.Center;
                            break;

                        case "right":
                            _format.align = AlignType.Right;
                            break;
                        }
                        if (!IsNewLine())
                        {
                            AppendText("\n");
                        }
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        AppendText("\n");
                        skipNextCR = true;

                        PopTextFormat();
                    }
                    break;

                case "ui":
                case "div":
                case "li":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        if (!IsNewLine())
                        {
                            AppendText("\n");
                        }
                    }
                    else
                    {
                        AppendText("\n");
                        skipNextCR = true;
                    }
                    break;

                case "html":
                case "body":
                    //full html
                    ignoreWhiteSpace = true;
                    break;

                case "head":
                case "style":
                case "script":
                case "form":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        skipText++;
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        skipText--;
                    }
                    break;
                }
            }

            if (skipText == 0)
            {
                text = XMLIterator.GetText(ignoreWhiteSpace);
                if (text.Length > 0)
                {
                    if (skipNextCR && text[0] == '\n')
                    {
                        text = text.Substring(1);
                    }
                    AppendText(text);
                }
            }

            _elements = null;
        }
示例#38
0
 public void DrawText(string text, TextFormat font, float x, float y, Brush brush, float width = 1000)
 {
     renderTarget.DrawText(text, font, new RawRectangleF(x, y, x + width, y + 1000), brush);
 }
示例#39
0
        public static void HealthBar(RenderTarget Device, DrawArea drawArea, Entity player)
        {
            using (SolidColorBrush brush = new SolidColorBrush(Device, Color.FromArgb(1, 1, 1).toRawColor4()))
            {
                var health = player.Health > 100 ? 100 : player.Health;

                var x  = drawArea.x - 5;
                var y1 = drawArea.y;
                var y2 = drawArea.y + drawArea.height;
                var y3 = drawArea.y + 1 + (drawArea.height - (health * (drawArea.height / 100)));
                var y4 = y2 - 1;

                if (visuals.HealthPostion == Settings.HealthDisplay.Right)
                {
                    x = drawArea.x + drawArea.width + 5;
                }
                else if (visuals.HealthPostion != Settings.HealthDisplay.Left)
                {
                    if (visuals.HealthPostion == Settings.HealthDisplay.Top)
                    {
                        x = drawArea.y - 5;
                    }
                    else
                    {
                        x = drawArea.y + drawArea.height + 5;
                    }

                    y1 = drawArea.x;
                    y2 = drawArea.x + drawArea.width;
                    y3 = drawArea.x - 1 + ((health * (drawArea.width / 100)));
                    y4 = y1 + 1;
                }

                if (visuals.HealthPostion == Settings.HealthDisplay.Left || visuals.HealthPostion == Settings.HealthDisplay.Right)
                {
                    Device.DrawLine(new RawVector2(x, y1), new RawVector2(x, y2), brush, 3);
                    brush.Color = player.Health.HealthToColor().toRawColor4();
                    Device.DrawLine(new RawVector2(x, y3), new RawVector2(x, y4), brush, 1);
                }
                else
                {
                    Device.DrawLine(new RawVector2(y1, x), new RawVector2(y2, x), brush, 3);
                    brush.Color = player.Health.HealthToColor().toRawColor4();
                    Device.DrawLine(new RawVector2(y3, x), new RawVector2(y4, x), brush, 1);
                }

                TextFormat txtForm = new TextFormat(new SharpDX.DirectWrite.Factory(),
                                                    "Calibri", FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 10);


                txtForm.SetWordWrapping(WordWrapping.NoWrap);

                RawRectangleF rect = new RawRectangleF();

                if (visuals.HealthPostion == Settings.HealthDisplay.Left)
                {
                    rect = new RawRectangleF(x - 25, y1, x, y1 + 10);
                }
                else if (visuals.HealthPostion == Settings.HealthDisplay.Right)
                {
                    rect = new RawRectangleF(x + 10, y1, x + 1, y1 + 10);
                }
                else if (visuals.HealthPostion == Settings.HealthDisplay.Top)
                {
                    rect = new RawRectangleF(y1, x - 15, y2, x);
                }
                else if (visuals.HealthPostion == Settings.HealthDisplay.Bottom)
                {
                    rect = new RawRectangleF(y1, x, y2, x);
                }

                if (visuals.HealthNumber)
                {
                    brush.Color = Color.FromArgb(1, 1, 1).toRawColor4();
                    Device.DrawText(player.Health + "%", txtForm, rect, brush, DrawTextOptions.NoSnap);

                    if (player.isTeam)
                    {
                        brush.Color = visColors.Team_Text.toRawColor4();
                    }
                    else
                    {
                        brush.Color = visColors.Enemy_Text.toRawColor4();
                    }

                    Device.DrawText(player.Health + "%", txtForm, rect, brush, DrawTextOptions.EnableColorFont | DrawTextOptions.DisableColorBitmapSnapping | DrawTextOptions.NoSnap);
                }
            }
        }
示例#40
0
        /// <summary>
        /// Look up and cross-link all field types etc.
        /// </summary>
        internal void CrossLink()
        {
            if (Proto.HasExtendee)
            {
                IDescriptor extendee = File.DescriptorPool.LookupSymbol(Proto.Extendee, this);
                if (!(extendee is MessageDescriptor))
                {
                    throw new DescriptorValidationException(this, "\"" + Proto.Extendee + "\" is not a message type.");
                }
                containingType = (MessageDescriptor)extendee;

                if (!containingType.IsExtensionNumber(FieldNumber))
                {
                    throw new DescriptorValidationException(this,
                                                            "\"" + containingType.FullName + "\" does not declare " + FieldNumber + " as an extension number.");
                }
            }

            if (Proto.HasTypeName)
            {
                IDescriptor typeDescriptor =
                    File.DescriptorPool.LookupSymbol(Proto.TypeName, this);

                if (!Proto.HasType)
                {
                    // Choose field type based on symbol.
                    if (typeDescriptor is MessageDescriptor)
                    {
                        fieldType  = FieldType.Message;
                        mappedType = MappedType.Message;
                    }
                    else if (typeDescriptor is EnumDescriptor)
                    {
                        fieldType  = FieldType.Enum;
                        mappedType = MappedType.Enum;
                    }
                    else
                    {
                        throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a type.");
                    }
                }

                if (MappedType == MappedType.Message)
                {
                    if (!(typeDescriptor is MessageDescriptor))
                    {
                        throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a message type.");
                    }
                    messageType = (MessageDescriptor)typeDescriptor;

                    if (Proto.HasDefaultValue)
                    {
                        throw new DescriptorValidationException(this, "Messages can't have default values.");
                    }
                }
                else if (MappedType == Descriptors.MappedType.Enum)
                {
                    if (!(typeDescriptor is EnumDescriptor))
                    {
                        throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not an enum type.");
                    }
                    enumType = (EnumDescriptor)typeDescriptor;
                }
                else
                {
                    throw new DescriptorValidationException(this, "Field with primitive type has type_name.");
                }
            }
            else
            {
                if (MappedType == MappedType.Message || MappedType == MappedType.Enum)
                {
                    throw new DescriptorValidationException(this, "Field with message or enum type missing type_name.");
                }
            }

            // We don't attempt to parse the default value until here because for
            // enums we need the enum type's descriptor.
            if (Proto.HasDefaultValue)
            {
                if (IsRepeated)
                {
                    throw new DescriptorValidationException(this, "Repeated fields cannot have default values.");
                }

                try {
                    switch (FieldType)
                    {
                    case FieldType.Int32:
                    case FieldType.SInt32:
                    case FieldType.SFixed32:
                        defaultValue = TextFormat.ParseInt32(Proto.DefaultValue);
                        break;

                    case FieldType.UInt32:
                    case FieldType.Fixed32:
                        defaultValue = TextFormat.ParseUInt32(Proto.DefaultValue);
                        break;

                    case FieldType.Int64:
                    case FieldType.SInt64:
                    case FieldType.SFixed64:
                        defaultValue = TextFormat.ParseInt64(Proto.DefaultValue);
                        break;

                    case FieldType.UInt64:
                    case FieldType.Fixed64:
                        defaultValue = TextFormat.ParseUInt64(Proto.DefaultValue);
                        break;

                    case FieldType.Float:
                        defaultValue = TextFormat.ParseFloat(Proto.DefaultValue);
                        break;

                    case FieldType.Double:
                        defaultValue = TextFormat.ParseDouble(Proto.DefaultValue);
                        break;

                    case FieldType.Bool:
                        if (Proto.DefaultValue == "true")
                        {
                            defaultValue = true;
                        }
                        else if (Proto.DefaultValue == "false")
                        {
                            defaultValue = false;
                        }
                        else
                        {
                            throw new FormatException("Boolean values must be \"true\" or \"false\"");
                        }
                        break;

                    case FieldType.String:
                        defaultValue = Proto.DefaultValue;
                        break;

                    case FieldType.Bytes:
                        try {
                            defaultValue = TextFormat.UnescapeBytes(Proto.DefaultValue);
                        } catch (FormatException e) {
                            throw new DescriptorValidationException(this, "Couldn't parse default value: " + e.Message);
                        }
                        break;

                    case FieldType.Enum:
                        defaultValue = enumType.FindValueByName(Proto.DefaultValue);
                        if (defaultValue == null)
                        {
                            throw new DescriptorValidationException(this, "Unknown enum default value: \"" + Proto.DefaultValue + "\"");
                        }
                        break;

                    case FieldType.Message:
                    case FieldType.Group:
                        throw new DescriptorValidationException(this, "Message type had default value.");
                    }
                } catch (FormatException e) {
                    DescriptorValidationException validationException =
                        new DescriptorValidationException(this, "Could not parse default value: \"" + Proto.DefaultValue + "\"", e);
                    throw validationException;
                }
            }
            else
            {
                // Determine the default default for this field.
                if (IsRepeated)
                {
                    defaultValue = Lists <object> .Empty;
                }
                else
                {
                    switch (MappedType)
                    {
                    case MappedType.Enum:
                        // We guarantee elsewhere that an enum type always has at least
                        // one possible value.
                        defaultValue = enumType.Values[0];
                        break;

                    case MappedType.Message:
                        defaultValue = null;
                        break;

                    default:
                        defaultValue = GetDefaultValueForMappedType(MappedType);
                        break;
                    }
                }
            }

            if (!IsExtension)
            {
                File.DescriptorPool.AddFieldByNumber(this);
            }

            if (containingType != null && containingType.Options.MessageSetWireFormat)
            {
                if (IsExtension)
                {
                    if (!IsOptional || FieldType != FieldType.Message)
                    {
                        throw new DescriptorValidationException(this, "Extensions of MessageSets must be optional messages.");
                    }
                }
                else
                {
                    throw new DescriptorValidationException(this, "MessageSets cannot have fields, only extensions.");
                }
            }
        }
示例#41
0
        public void CreatePDF(Stream stream)
        {
            var doc  = new GcPdfDocument();
            var page = doc.NewPage();
            var g    = page.Graphics;

            var rc = Common.Util.AddNote(
                "Vertical text often includes short runs of horizontal numbers or Latin text. " +
                "In CSS this is referred to using the Japanese name 縦中横 (tate chu yoko). " +
                "It occurs in Chinese, Japanese and Korean vertical text. " +
                "We support this by providing TextFormat.UprightInVerticalText and a few " +
                "related properties on TextLayout and TextFormat.",
                page);

            var fntJp      = Font.FromFile(Path.Combine("Resources", "Fonts", "YuGothM.ttc"));
            var fntLat     = Font.FromFile(Path.Combine("Resources", "Fonts", "MyriadPro-Cond.otf"));
            var hiliteFore = Color.DarkSlateBlue;
            var hiliteBack = Color.FromArgb(unchecked ((int)0xffffff99));

            var tl = g.CreateTextLayout();

            // Set text flow and other layout properties:
            tl.FlowDirection          = FlowDirection.VerticalRightToLeft;
            tl.MaxWidth               = page.Size.Width;
            tl.MaxHeight              = page.Size.Height;
            tl.MarginAll              = 72;
            tl.MarginTop              = rc.Bottom + 36;
            tl.ParagraphSpacing       = 12;
            tl.LineSpacingScaleFactor = 1.4f;

            // g.FillRectangle(
            // new RectangleF(tl.MarginLeft, tl.MarginTop, tl.MaxWidth.Value - tl.MarginLeft - tl.MarginRight, tl.MaxHeight.Value - tl.MarginTop - tl.MarginBottom),
            // Color.AliceBlue);

            // Text format for upright text (short Latin words or numbers)
            // (GlyphWidths turns on corresponding font features, but makes a difference
            // only of those features are present in the font):
            var fUpright = new TextFormat()
            {
                Font     = fntLat,
                FontSize = 14,
                UprightInVerticalText = true,
                GlyphWidths           = GlyphWidths.QuarterWidths,
                TextRunAsCluster      = true,
            };
            // Text format for vertical Japanese and sideways Latin text:
            var fVertical = new TextFormat(fUpright)
            {
                Font = fntJp,
                UprightInVerticalText = false,
                GlyphWidths           = GlyphWidths.Default,
                TextRunAsCluster      = false,
            };

            // Make sure runs of sideways text do not affect vertical spacing:
            fVertical.UseVerticalLineGapForSideways = true;
            // This commented fragment effectively would do the same as the
            // UseVerticalLineGapForSideways property setting above:

            /*
             * var scale = fVertical.FontSize * tl.FontScaleFactor / fntJp.UnitsPerEm;
             * if (!fVertical.FontSizeInGraphicUnits)
             *  scale *= tl.Resolution / 72f;
             * fVertical.LineGap = fntJp.VerticalLineGap * scale;
             */

            // Two additional text formants for highlighted headers:
            var fUpHdr = new TextFormat(fUpright)
            {
                ForeColor = hiliteFore,
                BackColor = hiliteBack
            };
            var fVertHdr = new TextFormat(fVertical)
            {
                ForeColor = hiliteFore,
                BackColor = hiliteBack
            };

            tl.Append("PDF", fUpright);
            tl.Append("ファイルをコードから", fVertical);
            tl.Append("API", fUpright);
            tl.Append("を利用することで操作できます。クロスプラットフォーム環境で動作するアプリケーションの開発を支援する", fVertical);
            tl.Append("API", fUpright);
            tl.Append("ライブラリです。", fVertical);

            // Smaller font size for the rest of the text:
            fUpright.FontSize  -= 2;
            fVertical.FontSize -= 2;

            // 1:
            tl.AppendParagraphBreak();
            tl.Append("PDF", fUpHdr);
            tl.Append("用の包括的な", fVertHdr);
            tl.Append("API", fUpHdr);

            tl.AppendSoftBreak();
            tl.Append("PDF", fUpright);
            tl.Append("バージョン「", fVertical);
            tl.Append("1.7", fUpright);
            tl.Append("」に準拠した", fVertical);
            tl.Append("API", fUpright);
            tl.Append("を提供し、レイアウトや機能を損なうことなく、豊富な機能を備えた", fVertical);
            tl.Append("PDF", fUpright);
            tl.Append("文書を生成、編集、保存できます。", fVertical);

            // 2:
            tl.AppendParagraphBreak();
            tl.Append("完全なテキスト描画", fVertHdr);

            tl.AppendSoftBreak();
            tl.Append("PDF", fUpright);
            tl.Append("文書にテキストの描画情報が保持されます。テキストと段落の書式、特殊文字、複数の言語、縦書き、テキスト角度などが保持さるので、完全な形でテキスト描画を再現できます。", fVertical);

            // 3:
            tl.AppendParagraphBreak();
            tl.Append(".NET Standard 2.0 準拠", fVertHdr);

            tl.AppendSoftBreak();
            tl.Append(".NET Core、.NET Framework、Xamarinで動作するアプリケーションを開発できます。Windows、macOS、Linuxなどクロスプラットフォーム環境で動作可能です。", fVertical);

            // 4:
            tl.AppendParagraphBreak();
            tl.Append("100", fUpHdr);
            tl.Append("を超える", fVertHdr);
            tl.Append("PDF", fUpHdr);
            tl.Append("操作機能", fVertHdr);

            tl.AppendSoftBreak();
            tl.Append("ページの追加や削除、ページサイズ、向きの変更だけでなく、ファイルの圧縮、", fVertical);
            tl.Append("Web", fUpright);
            tl.Append("に最適化した", fVertical);
            tl.Append("PDF", fUpright);
            tl.Append("の生成など高度な機能も", fVertical);
            tl.Append("API", fUpright);
            tl.Append("操作で実現します。また、署名からセキュリティ機能まで様々な機能を含んだ", fVertical);
            tl.Append("PDF", fUpright);
            tl.Append("フォームを生成可能です。", fVertical);

            // 5:
            tl.AppendParagraphBreak();
            tl.Append("高速、軽量アーキテクチャ", fVertHdr);

            tl.AppendSoftBreak();
            tl.Append("軽量", fVertical);
            tl.Append("API", fUpright);
            tl.Append("アーキテクチャでメモリと時間を節約できます。", fVertical);
            tl.AppendSoftBreak();
            tl.Append("また、他の生成用ツールに依存せずドキュメントを生成可能です。", fVertical);

            // 6:
            tl.AppendParagraphBreak();
            tl.Append("クラウドアプリケーション展開", fVertHdr);
            tl.Append("", fUpHdr);

            tl.AppendSoftBreak();
            tl.Append("Azure、AWSなどのサービスに配置するクラウドアプリケーションの開発で利用可能です。仮想マシン、コンテナ、サーバーレスなどの方法で配置できます。", fVertical);

            tl.PerformLayout(true);
            g.DrawTextLayout(tl, PointF.Empty);

            // Done:
            doc.Save(stream);
        }
示例#42
0
        public SizeF GetStringSize(
            string value,
            string fontName,
            float textSize,
            HorizontalAlignment horizontalAlignment,
            VerticalAlignment verticalAlignment)
        {
            if (value == null)
            {
                return(new SizeF());
            }

            float fontSize = textSize;
            float factor   = 1;

            while (fontSize > 14)
            {
                fontSize /= 14;
                factor   *= 14;
            }

            var size = new SizeF();

            var textFormat = new TextFormat(FactoryDirectWrite, SystemFontName, FontWeight.Regular, FontStyle.Normal,
                                            fontSize);

            if (horizontalAlignment == HorizontalAlignment.Left)
            {
                textFormat.TextAlignment = TextAlignment.Leading;
            }
            else if (horizontalAlignment == HorizontalAlignment.Center)
            {
                textFormat.TextAlignment = TextAlignment.Center;
            }
            else if (horizontalAlignment == HorizontalAlignment.Right)
            {
                textFormat.TextAlignment = TextAlignment.Trailing;
            }
            else if (horizontalAlignment == HorizontalAlignment.Justified)
            {
                textFormat.TextAlignment = TextAlignment.Justified;
            }

            if (verticalAlignment == VerticalAlignment.Top)
            {
                textFormat.ParagraphAlignment = ParagraphAlignment.Near;
            }
            else if (verticalAlignment == VerticalAlignment.Center)
            {
                textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            }
            else if (verticalAlignment == VerticalAlignment.Bottom)
            {
                textFormat.ParagraphAlignment = ParagraphAlignment.Far;
            }

            var textLayout = new TextLayout(FactoryDirectWrite, value, textFormat, 512f, 512f, Dip, false);

            size.Width  = textLayout.Metrics.Width;
            size.Height = textLayout.Metrics.Height;


            size.Width  *= factor;
            size.Height *= factor;

            return(size);
        }
示例#43
0
 /// <summary>
 /// Adds a new FormattedText object with the given text and format.
 /// </summary>
 public FormattedText AddFormattedText(string text, TextFormat textFormat)
 {
     return(Elements.AddFormattedText(text, textFormat));
 }
示例#44
0
 /// <summary>
 /// Adds a new FormattedText object with the given format.
 /// </summary>
 public FormattedText AddFormattedText(TextFormat textFormat)
 {
     return(Elements.AddFormattedText(textFormat));
 }
 public CSGOControl(CSGOTheme theme, TextFormat font, float x, float y)
     : this(theme, font, x, y, 100f, 100f)
 {
 }
示例#46
0
 public void DrawText(string text, TextFormat textFormat, RawRectangleF layoutRect, Brush defaultForegroundBrush) => _renderTarget?.DrawText(text, textFormat, layoutRect, defaultForegroundBrush);
 public CSGOControl(CSGOTheme theme, TextFormat font, float x, float y, float width, float height)
     : this(theme, font, x, y, width, height, true)
 {
 }
示例#48
0
        public void CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();

            // PDF format allows to insert JPEG and JPEG2000 images into the document 'as is',
            // without converting to PDF native image formats. To do that in GcPdf,
            // the RawImage class can be used, as the code below demonstrates.
            //
            // Create instances of RawImage from JPEG files:
            using (var image = RawImage.FromFile(Path.Combine("Resources", "Images", "puffins.jpg"), RawImageFormat.Jpeg, 800, 532))
                using (var imageSmall = RawImage.FromFile(Path.Combine("Resources", "ImagesBis", "puffins-small.jpg"), RawImageFormat.Jpeg, 144, 96))
                {
                    // Text format used to draw captions:
                    TextFormat tf = new TextFormat()
                    {
                        Font = StandardFonts.Times, FontSize = 12
                    };

                    // Action to draw the image using various options:
                    Action <RawImage, Page, ImageAlign, bool> drawImage = (image_, page_, ia_, clip_) =>
                    {
                        var rect    = new RectangleF(72, 72, 72 * 4, 72 * 4);
                        var clipped = clip_ ? "clipped to a 4\"x4\" rectangle" : "without clipping";
                        var align   = ia_ == ImageAlign.Default ? "ImageAlign.Default" :
                                      ia_ == ImageAlign.CenterImage ? "ImageAlign.CenterImage" :
                                      ia_ == ImageAlign.StretchImage ? "ImageAlign.StretchImage" : "custom ImageAlign";
                        // Draw image caption:
                        page_.Graphics.DrawString($"Page {doc.Pages.IndexOf(page_) + 1}: Image drawn at (1\",1\"), {clipped}, using {align}:", tf, new PointF(72, 36));
                        var clip = clip_ ? new Nullable <RectangleF>(rect) : new Nullable <RectangleF>();
                        // Draw the image:
                        page_.Graphics.DrawImage(image_, rect, clip, ia_, out RectangleF[] imageRects);
                        // Show the image outline:
                        page_.Graphics.DrawRectangle(imageRects[0], Color.Red, 1, null);
                        // Show image/clip area:
                        page_.Graphics.DrawRectangle(rect, Color.Blue, 1, null);
                    };

                    // The ImageAlign class provides various image alignment options.
                    // It also defines a few static instances with some commonly used
                    // combinations of options demonstrated below.

                    // Page 1: draw image without clipping, with default alignment:
                    drawImage(image, doc.NewPage(), ImageAlign.Default, false);

                    // Page 2: draw image with clipping, with default alignment:
                    drawImage(image, doc.NewPage(), ImageAlign.Default, true);

                    // Page 3: draw image with clipping, with CenterImage alignment:
                    drawImage(image, doc.NewPage(), ImageAlign.CenterImage, true);

                    // Page 4: draw image without clipping and stretched image:
                    drawImage(image, doc.NewPage(), ImageAlign.StretchImage, false);

                    // Page 5: draw image without clipping, fit into the rectangle, preserving aspect ratio:
                    ImageAlign ia = new ImageAlign(ImageAlignHorz.Center, ImageAlignVert.Center, true, true, true, false, false);
                    drawImage(image, doc.NewPage(), ia, false);

                    // Page 6: draw a small image tiled, without clipping, fit into the rectangle, preserving aspect ratio:
                    ia = new ImageAlign(ImageAlignHorz.Left, ImageAlignVert.Top, false, false, true, true, true);
                    drawImage(imageSmall, doc.NewPage(), ia, false);

                    // Done:
                    doc.Save(stream);
                }
        }
 public CSGOControl(CSGOTheme theme, TextFormat font, float x, float y, float width, float height, bool visible, bool enabled)
     : base(theme, font, x, y, width, height, visible, enabled)
 {
 }
示例#50
0
 public HtmlElement()
 {
     format = new TextFormat();
 }
示例#51
0
        public int CreatePDF(Stream stream)
        {
            GcPdfDocument doc  = new GcPdfDocument();
            Page          page = doc.NewPage();
            TextFormat    tf   = new TextFormat()
            {
                Font = StandardFonts.Times, FontSize = 14
            };

            page.Graphics.DrawString(
                "Hello, World!\r\nSigned below by GcPdfWeb VisualSignature sample.",
                tf, new PointF(72, 72));

            // Init a test certificate:
            var pfxPath           = Path.Combine("Resources", "Misc", "GcPdfTest.pfx");
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                                                         X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            SignatureProperties sp = new SignatureProperties();

            sp.Certificate = cert;
            sp.Location    = "GcPdfWeb Sample Browser";
            sp.SignerName  = "GcPdfWeb";

            // Add an image representing the signature:
            sp.SignatureAppearance.Image = Image.FromFile(Path.Combine("Resources", "ImagesBis", "signature.png"));
            sp.SignatureAppearance.CaptionImageRelation = GrapeCity.Documents.Pdf.Annotations.CaptionImageRelation.ImageOnly;

            // Init a signature field to hold the signature:
            SignatureField sf = new SignatureField();

            sf.Widget.Rect                     = new RectangleF(72, 72 * 2, 72 * 4, 36);
            sf.Widget.Page                     = page;
            sf.Widget.BackColor                = Color.LightSeaGreen;
            sf.Widget.TextFormat.Font          = StandardFonts.Helvetica;
            sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}\r\nLocation: {sp.Location}";
            // Add the signature field to the document:
            doc.AcroForm.Fields.Add(sf);
            // Connect the signature field and signature props:
            sp.SignatureField = sf;

            // Sign and save the document:
            // NOTES:
            // - Signing and saving is an atomic operation, the two cannot be separated.
            // - The stream passed to the Sign() method must be readable.
            doc.Sign(sp, stream);

            // Rewind the stream to read the document just created
            // into another GcPdfDocument and verify the signature:
            stream.Seek(0, SeekOrigin.Begin);
            GcPdfDocument doc2 = new GcPdfDocument();

            doc2.Load(stream);
            SignatureField sf2 = (SignatureField)doc2.AcroForm.Fields[0];

            if (!sf2.Value.VerifySignature())
            {
                throw new Exception("Failed to verify the signature");
            }

            // Done (the generated and signed document has already been saved to 'stream').
            return(doc.Pages.Count);
        }
示例#52
0
        protected override SimpleNode CreateInternal(object data)
        {
            _isAsItIS = false;
            var tableCell = new SimpleNode(_nodeName, "");

            tableCell.Classes.Add("col-" + _colId);

            double number;

            data = data ?? "0";
            double.TryParse(data.ToString(), out number);

            string result = "";

            if (Prefix != null)
            {
                result += Prefix;
            }

            if (!string.IsNullOrEmpty(NumberFormatString))
            {
                _numberFormatter = new TextFormat()
                {
                    FormatString = NumberFormatString
                };
                if (Suffix != null && Suffix == "k" && Math.Abs(number) < 1000)
                {
                    _numberFormatter = new TextFormat()
                    {
                        FormatString = "#,##0"
                    };
                    _isAsItIS = true;
                }

                var formattedValue = _numberFormatter.Format(Math.Abs(number).ToString(CultureInfo.InvariantCulture));
                result += formattedValue;
            }
            else
            {
                result += Math.Abs(number).ToString(CultureInfo.InvariantCulture);
            }

            if (Suffix != null)
            {
                if (_isAsItIS)
                {
                    result += "";
                }
                else
                {
                    result += Suffix;
                }
            }

            if (string.IsNullOrEmpty(data.ToString()))
            {
                return(tableCell);
            }

            tableCell = new SimpleNode(_nodeName, result);
            tableCell.Classes.Add("col-" + _colId);

            return(tableCell);
        }
示例#53
0
 public ESP(CSGOTheme theme, TextFormat font)
     : base(theme, font)
 {
     once = true;
 }
示例#54
0
 public override void DevIndepAcquire()
 {
     Lyric_TextFormat = TextFormat("Arial", 10);
 }
 /// <summary>
 /// Draws the specified text using the format information provided by an <see cref="T:SharpDX.DirectWrite.TextFormat" /> object.
 /// </summary>
 /// <remarks>
 /// To create an <see cref="T:SharpDX.DirectWrite.TextFormat" /> object, create an <see cref="T:SharpDX.DirectWrite.Factory" /> and call its {{CreateTextFormat}} method. This method doesn't return an error code if it fails. To determine whether a drawing operation (such as {{DrawText}}) failed, check the result returned by the <see cref="M:SharpDX.Direct2D1.RenderTarget.EndDraw(System.Int64@,System.Int64@)" /> or <see cref="M:SharpDX.Direct2D1.RenderTarget.Flush(System.Int64@,System.Int64@)" /> methods.
 /// </remarks>
 /// <param name="text">A reference to an array of Unicode characters to draw.  </param>
 /// <param name="textFormat">An object that describes formatting details of the text to draw, such as the font, the font size, and flow direction.   </param>
 /// <param name="layoutRect">The size and position of the area in which the text is drawn.  </param>
 /// <param name="defaultForegroundBrush">The brush used to paint the text. </param>
 /// <param name="options">A value that indicates whether the text should be snapped to pixel boundaries and whether the text should be clipped to the layout rectangle. The default value is <see cref="F:SharpDX.Direct2D1.DrawTextOptions.None" />, which indicates that text should be snapped to pixel boundaries and it should not be clipped to the layout rectangle. </param>
 /// <unmanaged>void ID2D1RenderTarget::DrawTextA([In, Buffer] const wchar_t* string,[None] int stringLength,[In] IDWriteTextFormat* textFormat,[In] const D2D1_RECT_F* layoutRect,[In] ID2D1Brush* defaultForegroundBrush,[None] D2D1_DRAW_TEXT_OPTIONS options,[None] DWRITE_MEASURING_MODE measuringMode)</unmanaged>
 public void DrawText(string text, TextFormat textFormat, RawRectangleF layoutRect, Brush defaultForegroundBrush, DrawTextOptions options)
 {
     DrawText(text, text.Length, textFormat, layoutRect, defaultForegroundBrush, options, MeasuringMode.Natural);
 }
示例#56
0
 public float MeasureString(string text, TextFormat font)
 {
     using (TextLayout layout = new TextLayout(directWriteFactory, text, font, 1000, 1000))
         return((float)layout.Metrics.WidthIncludingTrailingWhitespace);
 }
示例#57
0
 public override void DevIndepRelease()
 {
     Lyric_TextFormat = null;
 }
示例#58
0
        //******************************************************
        //GetText
        //******************************************************
        /// <summary>
        ///    <para>Returns a textual representation of the object in the specified format.</para>
        /// </summary>
        /// <param name='format'>The requested textual format. </param>
        /// <returns>
        ///    <para>The textual representation of the
        ///       object in the specified format.</para>
        /// </returns>
        //
        public string GetText(TextFormat format)
        {
            string objText = null;
            int    status  = (int)ManagementStatus.NoError;

            //
            // Removed Initialize call since wbemObject is a property that will call Initialize ( true ) on
            // its getter.
            //
            switch (format)
            {
            case TextFormat.Mof:

                status = wbemObject.GetObjectText_(0, out objText);

                if (status < 0)
                {
                    if ((status & 0xfffff000) == 0x80041000)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(status);
                    }
                }

                return(objText);

            case TextFormat.CimDtd20:
            case TextFormat.WmiDtd20:

                //This may throw on non-XP platforms... - should we catch ?
                IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc) new WbemObjectTextSrc();
                IWbemContext       ctx         = (IWbemContext) new WbemContext();
                object             v           = (bool)true;
                ctx.SetValue_("IncludeQualifiers", 0, ref v);
                ctx.SetValue_("IncludeClassOrigin", 0, ref v);

                if (wbemTextSrc != null)
                {
                    status = wbemTextSrc.GetText_(0,
                                                  (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)),
                                                  (uint)format, //note: this assumes the format enum has the same values as the underlying WMI enum !!
                                                  ctx,
                                                  out objText);
                    if (status < 0)
                    {
                        if ((status & 0xfffff000) == 0x80041000)
                        {
                            ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                        }
                        else
                        {
                            Marshal.ThrowExceptionForHR(status);
                        }
                    }
                }

                return(objText);

            default:

                return(null);
            }
        }
示例#59
0
 public void DrawText(string text, TextFormat textFormat, RawRectangleF layoutRect, Brush defaultForegroundBrush, DrawTextOptions options, MeasuringMode measuringMode) => _renderTarget?.DrawText(text, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode);
示例#60
0
 public string GetText(TextFormat format)
 {
     throw new NotImplementedException();
 }