Exemplo n.º 1
0
        static string MidTruncatedIter(string text, TextPaint paint, int secondToLastEnd, int startLastVisible, int midLastVisible, int startLow, int startHigh, int end, float availWidth)
        {
            if (startHigh - startLow <= 1)
            {
                return((secondToLastEnd > 0 ? text.Substring(0, secondToLastEnd).TrimEnd() + "\n" : "") + text.Substring(startLastVisible, midLastVisible - startLastVisible).TrimEnd() + "…" + text.Substring(startHigh, end - startHigh).TrimStart());
            }
            int mid          = (startLow + startHigh) / 2;
            var lastLineText = new Java.Lang.String(text.Substring(startLastVisible, midLastVisible - startLastVisible).TrimEnd() + "…" + text.Substring(mid, end - mid).TrimStart());
            //var truncBounds = new Android.Graphics.Rect();
            //paint.GetTextBounds(lastLineText, 0, lastLineText.Length, truncBounds);
            //if (truncBounds.Width() > availWidth)
            var layout = new StaticLayout(lastLineText, paint, int.MaxValue - 10000, Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, true);

            if (layout.GetLineWidth(0) > availWidth)
            {
                return(MidTruncatedIter(text, paint, secondToLastEnd, startLastVisible, midLastVisible, mid, startHigh, end, availWidth));
            }
            return(MidTruncatedIter(text, paint, secondToLastEnd, startLastVisible, midLastVisible, startLow, mid, end, availWidth));
        }
        public static StaticLayout CreateLayout(string text, TextPaint textPaint, int?boundedWidth, Layout.Alignment alignment)
        {
            int finalWidth = int.MaxValue;

            if (boundedWidth > 0)
            {
                finalWidth = (int)boundedWidth;
            }

            var layout = new StaticLayout(
                text,       // Text to layout
                textPaint,  // Text paint (font, size, etc...) to use
                finalWidth, // The maximum width the text can be
                alignment,  // The horizontal alignment of the text
                1.0f,       // Spacing multiplier
                0.0f,       // Additional spacing
                false);     // Include padding

            return(layout);
        }
Exemplo n.º 3
0
        private void MeasureContent()
        {
            //If drawing to a path, we cannot measure intrinsic bounds
            //We must rely on setBounds being called externally
            if (_textPath != null)
            {
                //Clear any previous measurement
                _textLayout = null;
                _textBounds.SetEmpty();
            }
            else
            {
                //Measure text bounds
                double desired = Math.Ceiling(Layout.GetDesiredWidth(_text, _textPaint));
                _textLayout = new StaticLayout(_text, _textPaint, (int)desired, _textAlignment, 1.0f, 0.0f, false);
                _textBounds.Set(0, 0, _textLayout.Width, _textLayout.Height);
            }

            //We may need to be redrawn
            this.InvalidateSelf();
        }
Exemplo n.º 4
0
        public static SizeF GetTextSizeAsSizeF(this StaticLayout target, bool hasBoundedWidth)
        {
            // We need to know if the static layout was created with a bounded width, as this is what
            // StaticLayout.Width returns.
            if (hasBoundedWidth)
            {
                return(new SizeF(target.Width, target.Height));
            }

            float maxWidth  = 0;
            int   lineCount = target.LineCount;

            for (int i = 0; i < lineCount; i++)
            {
                float lineWidth = target.GetLineWidth(i);
                if (lineWidth > maxWidth)
                {
                    maxWidth = lineWidth;
                }
            }

            return(new SizeF(maxWidth, target.Height));
        }
        public static Drawing.SizeF GetTextSize(this StaticLayout target, bool hasBoundedWidth)
        {
            // We need to know if the static layout was created with a bounded width, as this is what
            // StaticLayout.Width returns.
            if (hasBoundedWidth)
            {
                return(new Drawing.SizeF(target.Width, target.Height));
            }

            float vMaxWidth  = 0;
            int   vLineCount = target.LineCount;

            for (int i = 0; i < vLineCount; i++)
            {
                float vLineWidth = target.GetLineWidth(i);
                if (vLineWidth > vMaxWidth)
                {
                    vMaxWidth = vLineWidth;
                }
            }

            return(new Drawing.SizeF(vMaxWidth, target.Height));
        }
Exemplo n.º 6
0
        private bool DrawText(Canvas c, RectF rect, TextPaint textPaint, Rect r, int iconBottom)
        {
            c.Save();

            StaticLayout sl;

            if (Build.VERSION.SdkInt > BuildVersionCodes.M)
            {
                sl = StaticLayout.Builder.Obtain(Text, 0, Text.Length, textPaint, Math.Abs((int)rect.Width()))
                     .SetMaxLines(2)
                     .SetLineSpacing(1, 1)
                     .SetIncludePad(false)
                     .SetEllipsize(TextUtils.TruncateAt.End)
                     .SetAlignment(Layout.Alignment.AlignCenter)
                     .Build();
            }
            else
            {
                sl = new StaticLayout(Text, textPaint, Math.Abs((int)rect.Width()), Layout.Alignment.AlignCenter, 1, 1, false);
            }

            using (sl)
            {
                //float y = rect.Top + rect.Height() / 2 + GetTop(rect.Height(), r.Height()) - sl.Height / 2;
                float y = iconBottom;
                if (r.Width() / 2 > rect.Width())
                {
                    return(false);
                }

                c.Translate(rect.Left, y);
                sl.Draw(c);
                c.Restore();
            }

            return(true);
        }
Exemplo n.º 7
0
        private void DrawScaledText(Canvas canvas, int lineStart, String line, float lineWidth)
        {
            float x = 0;

            if (IsFirstLineOfParagraph(lineStart, line))
            {
                String blanks = "  ";
                canvas.DrawText(blanks, x, mLineY, Paint);
                float bw = StaticLayout.GetDesiredWidth(blanks, Paint);
                x += bw;

                line = line.Substring(3);
            }

            float d = (mViewWidth - lineWidth) / line.Length - 1;

            for (int i = 0; i < line.Length; i++)
            {
                String c  = line[i].ToString();
                float  cw = StaticLayout.GetDesiredWidth(c, Paint);
                canvas.DrawText(c, x, mLineY, Paint);
                x += cw + d;
            }
        }
Exemplo n.º 8
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
                return new CCTexture2D();

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize *= contentScaleFactorWidth;
            textDef.Dimensions.Width *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            var display = Game.Activity.WindowManager.DefaultDisplay;
            var metrics = new DisplayMetrics();
            display.GetMetrics(metrics);

            // Do not take into account ScaleDensity for now.
//            var fontScaleFactor = metrics.ScaledDensity;
//            textDef.FontSize = (int)(textDef.FontSize * fontScaleFactor);


            // out paint object to hold our drawn text
//            var paintFlags = new PaintFlags();
//            if (textDefinition.isShouldAntialias)
//                paintFlags = PaintFlags.AntiAlias | PaintFlags.SubpixelText;
            
            var textPaint = new TextPaint();
            textPaint.Color = Android.Graphics.Color.White;
            textPaint.TextAlign = Paint.Align.Left;
            textPaint.AntiAlias = textDefinition.isShouldAntialias;

            textPaint.TextSize = textDef.FontSize;

            var fontName = textDef.FontName;
            var ext = System.IO.Path.GetExtension(fontName);
            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                
                CCContentManager.SharedContentManager.GetAssetStreamAsBytes(fontName, out fontName);

                var activity = Game.Activity;

                try
                {
                    var typeface = Typeface.CreateFromAsset(activity.Assets, fontName);
                    textPaint.SetTypeface(typeface);
                }
                catch (Exception)
                {
                    textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
                }
            }
            else
            {
                textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
            }

            // color
            var foregroundColor = Android.Graphics.Color.White;

            textPaint.Color = foregroundColor;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? Layout.Alignment.AlignOpposite
                : (CCTextAlignment.Center == horizontalAlignment) ? Layout.Alignment.AlignCenter
                : Layout.Alignment.AlignNormal;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;
            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable = false;
            }


            // Get bounding rectangle - we need its attribute and method values
            var layout = new StaticLayout(text, textPaint, 
                (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);

            var boundingRect = new Rect();
            var lineBounds = new Rect();

            // Loop through all the lines so we can find our drawing offsets
            var lineCount = layout.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
                return new CCTexture2D();

            for (int lc = 0; lc < lineCount; lc++)
            {
                layout.GetLineBounds(lc, lineBounds);
                var max = (int)Math.Ceiling(layout.GetLineMax(lc));

                if (boundingRect.Right < max)
                    boundingRect.Right = max;

                boundingRect.Bottom = lineBounds.Bottom;
            }

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Right;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Bottom;
                }
            }

            imageWidth = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != Layout.Alignment.AlignNormal)
            {
                layout = new StaticLayout(text, textPaint, 
                    (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);
              
            }


            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement 
                || boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom  // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                    // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                   // align to center

            try {

                // Create our platform dependant image to be drawn to.
                using (Bitmap textureBitmap = Bitmap.CreateBitmap(imageWidth, imageHeight, Bitmap.Config.Argb8888))
                {
                    using (Canvas drawingCanvas = new Canvas(textureBitmap))
                    {
                        drawingCanvas.DrawARGB(0, 255, 255, 255);

                        // Set our vertical alignment
                        drawingCanvas.Translate(0, yOffset);

                        // Now draw the text using our layout
                        layout.Draw(drawingCanvas);

                        // Create a pixel array
                        int[] pixels = new int[imageWidth * imageHeight];

                        // Now lets get our pixels.
                        // We use CopyPixelsToBuffer so that it is in Premultiplied Alpha already.
                        // Using Bitmap.GetPixels return non Premultiplied Alpha which causes blending problems
                        Java.Nio.IntBuffer byteBuffer = Java.Nio.IntBuffer.Allocate(imageWidth * imageHeight);
                        textureBitmap.CopyPixelsToBuffer(byteBuffer);
                        if (byteBuffer.HasArray)
                        {
                            byteBuffer.Rewind();
                            byteBuffer.Get(pixels, 0, pixels.Length);
                        }

                        // Make sure we recycle - Let's keep it green
                        textureBitmap.Recycle();

                        // Here we create our Texture and then set our pixel data.
                        var texture = new CCTexture2D(imageWidth, imageHeight);
                        texture.XNATexture.SetData<int>(pixels);

                        return texture;
                    }
                }   
            }
            catch (Exception exc)
            {
                CCLog.Log ("CCLabel Android: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace);
                return new CCTexture2D();
            }
        }
Exemplo n.º 9
0
		protected override void OnDraw (Canvas canvas)
		{
			
			var scale = this.Context.Resources.DisplayMetrics.Density;

			var frame = GetFramingRect();
			if (frame == null)
				return;

			var width = canvas.Width;
			var height = canvas.Height;

			paint.Color = resultBitmap != null ? resultColor : maskColor;
			paint.Alpha = 100;

			canvas.DrawRect(0, 0, width, frame.Top, paint);
			//canvas.DrawRect(0, frame.Top, frame.Left, frame.Bottom + 1, paint);
			//canvas.DrawRect(frame.Right + 1, frame.Top, width, frame.Bottom + 1, paint);
			canvas.DrawRect(0, frame.Bottom + 1, width, height, paint);

		
			var textPaint = new TextPaint();
			textPaint.Color = Color.White;
			textPaint.TextSize = 16 * scale;

			var topTextLayout = new StaticLayout(this.TopText, textPaint, canvas.Width, Android.Text.Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
			canvas.Save();
			Rect topBounds = new Rect();

			textPaint.GetTextBounds(this.TopText, 0, this.TopText.Length, topBounds);
			canvas.Translate(0, frame.Top / 2 - (topTextLayout.Height / 2));

			//canvas.Translate(topBounds.Left, topBounds.Bottom);
			topTextLayout.Draw(canvas);

			canvas.Restore();


			var botTextLayout = new StaticLayout(this.BottomText, textPaint, canvas.Width, Android.Text.Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
			canvas.Save();
			Rect botBounds = new Rect();
			
			textPaint.GetTextBounds(this.BottomText, 0, this.BottomText.Length, botBounds);
			canvas.Translate(0, (frame.Bottom + (canvas.Height - frame.Bottom) / 2) - (botTextLayout.Height / 2));
			
			//canvas.Translate(topBounds.Left, topBounds.Bottom);
			botTextLayout.Draw(canvas);
			
			canvas.Restore();





			if (resultBitmap != null)
			{
				paint.Alpha = CURRENT_POINT_OPACITY;
				canvas.DrawBitmap(resultBitmap, null, new RectF(frame.Left, frame.Top, frame.Right, frame.Bottom), paint);
			}
			else
			{
				 // Draw a two pixel solid black border inside the framing rect
				paint.Color = frameColor;
				//canvas.DrawRect(frame.Left, frame.Top, frame.Right + 1, frame.Top + 2, paint);
				//canvas.DrawRect(frame.Left, frame.Top + 2, frame.Left + 2, frame.Bottom - 1, paint);
				//canvas.DrawRect(frame.Right - 1, frame.Top, frame.Right + 1, frame.Bottom - 1, paint);
				//canvas.DrawRect(frame.Left, frame.Bottom - 1, frame.Right + 1, frame.Bottom + 1, paint);

				// Draw a red "laser scanner" line through the middle to show decoding is active
				paint.Color = laserColor;
				paint.Alpha = SCANNER_ALPHA[scannerAlpha];
				scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.Length;
				int middle = frame.Height() / 2 + frame.Top;
				//int middle = frame.Width() / 2 + frame.Left;

				//canvas.DrawRect(frame.Left + 2, middle - 1, frame.Right - 1, middle + 2, paint);

				canvas.DrawRect(0, middle - 1, width, middle + 2, paint);
				//canvas.DrawRect(middle - 1, frame.Top + 2, middle + 2, frame.Bottom - 1, paint); //frame.Top + 2, middle - 1, frame.Bottom - 1, middle + 2, paint);

				//var previewFrame = scanner.GetFramingRectInPreview();
      			//float scaleX = frame.Width() / (float) previewFrame.Width();
      			//float scaleY = frame.Height() / (float) previewFrame.Height();

				/*var currentPossible = possibleResultPoints;
				var currentLast = lastPossibleResultPoints;

				int frameLeft = frame.Left;
				int frameTop = frame.Top;

				if (currentPossible == null || currentPossible.Count <= 0) 
				{
        			lastPossibleResultPoints = null;
				} 
				else 
				{
					possibleResultPoints = new List<com.google.zxing.ResultPoint>(5);
					lastPossibleResultPoints = currentPossible;
					paint.Alpha = CURRENT_POINT_OPACITY;
					paint.Color = resultPointColor;

					lock (currentPossible) 
					{
						foreach (var point in currentPossible) 
						{
							canvas.DrawCircle(frameLeft + (int) (point.X * scaleX),
                              frameTop + (int) (point.Y * scaleY), POINT_SIZE, paint);
						}
					}
				}

				if (currentLast != null) 
				{
					paint.Alpha = CURRENT_POINT_OPACITY / 2;
					paint.Color = resultPointColor;

					lock (currentLast) 
					{
						float radius = POINT_SIZE / 2.0f;
						foreach (var point in currentLast) 
						{
							canvas.DrawCircle(frameLeft + (int) (point.X * scaleX),
                              frameTop + (int) (point.Y * scaleY), radius, paint);
						}
					}
				}
				*/

				// Request another update at the animation interval, but only repaint the laser line,
				// not the entire viewfinder mask.
				PostInvalidateDelayed(ANIMATION_DELAY,
				                      frame.Left - POINT_SIZE,
				                      frame.Top - POINT_SIZE,
				                      frame.Right + POINT_SIZE,
				                      frame.Bottom + POINT_SIZE);
			}

			base.OnDraw (canvas);
		}
Exemplo n.º 10
0
 // Set the text size of the text paint object and use a static layout to render text off screen before measuring
 private int GetTextWidth(string source, TextPaint paint, int width, float textSize)
 {
     // Update the text paint object
     paint.TextSize = textSize;
     // Draw using a static layout
     StaticLayout layout = new StaticLayout(source, paint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, true);
     layout.Draw(TextResizeCanvas);
     return layout.Width;
 }
 // Set the text size of the text paint object and use a static layout to render text off screen before measuring
 private int GetTextHeight(string source, TextPaint paint, int width, float textSize)
 {
     // Update the text paint object
     paint.TextSize = textSize;
     // Measure using a static layout
     StaticLayout layout = new StaticLayout(source, paint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, true);
     return layout.Height;
 }
Exemplo n.º 12
0
        public void ResizeText(int width, int height)
        {
            var text = TextFormatted;

            if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || mTextSize == 0)
            {
                return;
            }

            if (TransformationMethod != null)
            {
                text = TransformationMethod.GetTransformationFormatted(TextFormatted, this);
            }

            TextPaint textPaint = Paint;

            float oldTextSize    = textPaint.TextSize;
            float targetTextSize = mMaxTextSize > 0 ? System.Math.Min(mTextSize, mMaxTextSize) : mTextSize;

            int textHeight = GetTextHeight(text, textPaint, width, targetTextSize);

            while (textHeight > height && targetTextSize > mMinTextSize)
            {
                targetTextSize = System.Math.Max(targetTextSize - 2, mMinTextSize);
                textHeight     = GetTextHeight(text, textPaint, width, targetTextSize);
            }

            if (AddEllipsis && targetTextSize == mMinTextSize && textHeight > height)
            {
                TextPaint paint = new TextPaint(textPaint);

                StaticLayout layout = new StaticLayout(text, paint, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
                if (layout.LineCount > 0)
                {
                    int lastLine = layout.GetLineForVertical(height) - 1;
                    if (lastLine < 0)
                    {
                        SetText("", BufferType.Normal);
                    }
                    else
                    {
                        int   start        = layout.GetLineStart(lastLine);
                        int   end          = layout.GetLineEnd(lastLine);
                        float lineWidth    = layout.GetLineWidth(lastLine);
                        float ellipseWidth = textPaint.MeasureText(mEllipsis);

                        while (width < lineWidth + ellipseWidth)
                        {
                            lineWidth = textPaint.MeasureText(text.SubSequence(start, --end + 1).ToString());
                        }
                        SetText(text.SubSequence(0, end) + mEllipsis, BufferType.Normal);
                    }
                }
            }

            SetTextSize(ComplexUnitType.Px, targetTextSize);
            SetLineSpacing(mSpacingAdd, mSpacingMult);

            mTextResizeListener?.OnTextResize(this, oldTextSize, targetTextSize);

            mNeedsResize = false;
        }
Exemplo n.º 13
0
        // Test if the suggested size fits the control boundaries
        public int OnTestSize(int suggestedSize, RectF availableSpace)
        {
            RectF textRect = new RectF();

            paint.TextSize = suggestedSize;
            ITransformationMethod transformationMethod = targetControl.TransformationMethod;
            string text = null;

            if (transformationMethod != null)
            {
                text = transformationMethod.GetTransformation(targetControl.Text, targetControl);
            }

            // If text is null, use the value from Text object
            if (text == null)
            {
                text = targetControl.Text;
            }

            bool singleLine = targetControl.MaxLines == 1;

            if (singleLine)
            {
                textRect.Bottom = paint.FontSpacing;
                textRect.Right  = paint.MeasureText(text);
            }
            else
            {
                StaticLayout layout = new StaticLayout(text, paint, widthLimit, Alignment.AlignNormal, spacingMult, spacingAdd, true);

                if (targetControl.MaxLines != NO_LINE_LIMIT && layout.LineCount > targetControl.MaxLines)
                {
                    return(1);
                }

                textRect.Bottom = layout.Height;
                int maxWidth  = -1;
                int lineCount = layout.LineCount;
                for (int i = 0; i < lineCount; i++)
                {
                    int end = layout.GetLineEnd(i);
                    if (i < lineCount - 1 && end > 0 && !IsValidWordWrap(text[end - 1], text[end]))
                    {
                        return(1);
                    }
                    if (maxWidth < layout.GetLineRight(i) - layout.GetLineLeft(i))
                    {
                        maxWidth = (int)layout.GetLineRight(i) - (int)layout.GetLineLeft(i);
                    }
                }
                textRect.Right = maxWidth;
            }
            textRect.OffsetTo(0, 0);

            if (availableSpace.Contains(textRect))
            {
                return(-1);
            }

            return(1);
        }
Exemplo n.º 14
0
        private Stream CreateBitmap(string text, LanguageIndex languageIndex, PaperSizeIndex paperSizeIndex)
        {
            Dictionary <LanguageIndex, Dictionary <PaperSizeIndex, int> > sizeDictionary = new Dictionary <LanguageIndex, Dictionary <PaperSizeIndex, int> >()
            {
                { LanguageIndex.English, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 25 }, { PaperSizeIndex.FourInch, 23 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.Japanese, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.French, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 24 }, { PaperSizeIndex.ThreeInch, 25 }, { PaperSizeIndex.FourInch, 25 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.Portuguese, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 24 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.Spanish, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.German, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 24 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.Russian, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 25 }, { PaperSizeIndex.FourInch, 25 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.SimplifiedChinese, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } },
                { LanguageIndex.TraditionalChinese, new Dictionary <PaperSizeIndex, int>()
                  {
                      { PaperSizeIndex.TwoInch, 22 }, { PaperSizeIndex.ThreeInch, 24 }, { PaperSizeIndex.FourInch, 24 }, { PaperSizeIndex.EscPosThreeInch, 24 }
                  } }
            };

            Paint paint = new Paint();

            paint.TextSize = sizeDictionary[languageIndex][paperSizeIndex];

            Typeface typeface = Typeface.Create(Typeface.Monospace, TypefaceStyle.Normal);

            paint.SetTypeface(typeface);

            paint.GetTextBounds(text, 0, text.Length, new Rect());

            TextPaint textPaint = new TextPaint(paint);

            StaticLayout staticLayout = new StaticLayout(text, textPaint, (int)paperSizeIndex, Android.Text.Layout.Alignment.AlignNormal, 1, 0, false);

            Bitmap bitmap = Bitmap.CreateBitmap(staticLayout.Width, staticLayout.Height, Bitmap.Config.Argb8888);

            Canvas canvas = new Canvas(bitmap);

            canvas.DrawColor(Android.Graphics.Color.White);

            canvas.Translate(0, 0);

            staticLayout.Draw(canvas);

            MemoryStream memoryStream = new MemoryStream();

            bitmap.Compress(Bitmap.CompressFormat.Png, 100, memoryStream);

            memoryStream.Seek(0, SeekOrigin.Begin);

            return(memoryStream);
        }
        private async Task UpdateNotifications()
        {
            this._notificationManager.CancelAll();

            var res = Resources;
            var largeIcon = BitmapFactory.DecodeResource(res, Resource.Drawable.LargeIconEmpty);
            var colorAccent = Resources.GetColor(Resource.Color.Accent);
            var colorAccentDark = Resources.GetColor(Resource.Color.AccentDark);

            var timetable = ApplicationMain.ServiceLocator.GetInstance<Timetable>();
            var timetableDataset = await timetable.GetDatasetAsync().ConfigureAwait(false);
            var now = LogicalDateTime.Now;

            // 番組と番組の画像のマッピング
            var mapping = await GetProgramImageMappingAsync().ConfigureAwait(false);

            // 最新と次の番組をとってくる
            foreach (var program in timetableDataset.Data[now.DayOfWeek].Where(x => x.End >= now.Time).Take(2))
            {
                var isNowPlaying = program.IsNowPlaying;
                var intent = new Intent(this.ApplicationContext, typeof(MainActivity));
                var builder = new Notification.Builder(this.ApplicationContext)
                    .SetContentTitle(program.Title)
                    .SetContentText(isNowPlaying ? $"現在放送中: {program.End.ToString("hh\\:mm")}まで" : $"もうすぐスタート: {program.Start.ToString("hh\\:mm")}から")
                    .SetPriority((int)(isNowPlaying ? NotificationPriority.Max : NotificationPriority.Default))
                    .SetLocalOnly(true)
                    .SetOngoing(true)
                    .SetCategory(Notification.CategoryRecommendation)
                    .SetLargeIcon(largeIcon)
                    .SetSmallIcon(Resource.Drawable.SmallIcon)
                    .SetContentIntent(PendingIntent.GetActivity(this.ApplicationContext, 0, intent, PendingIntentFlags.UpdateCurrent))
                    .SetColor(colorAccentDark);

                var builderBigPicture = new Notification.BigPictureStyle(builder);

                try
                {
                    // 画像があればそれを使うしなければ文字を描画するぞい
                    if (mapping.ContainsKey(program.MailAddress) || mapping.ContainsKey(program.Title))
                    {
                        var imageUrl = mapping.ContainsKey(program.MailAddress)
                            ? mapping[program.MailAddress]
                            : mapping[program.Title];

                        using (var httpClient = new HttpClient())
                        using (var stream = await httpClient.GetStreamAsync(imageUrl).ConfigureAwait(false))
                        {
                            var bitmap = BitmapFactory.DecodeStream(stream);
                            builder.SetLargeIcon(bitmap);
                            builderBigPicture.BigPicture(bitmap);
                        }
                    }
                    else
                    {
                        var width = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationEmptyWidth);
                        var height = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationEmptyHeight);
                        var textSize = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationTextSize);
                        textSize = Resources.DisplayMetrics.ToDevicePixel(textSize);
                        width = Resources.DisplayMetrics.ToDevicePixel(width);
                        height = Resources.DisplayMetrics.ToDevicePixel(height);
                        var bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                        using (var paint = new Paint() { TextSize = textSize, Color = Color.White, AntiAlias = true })
                        using (var textPaint = new TextPaint() { TextSize = textSize, Color = Color.White, AntiAlias = true })
                        using (var canvas = new Canvas(bitmap))
                        {
                            canvas.Save();

                            paint.Color = colorAccent;
                            canvas.DrawRect(0, 0, bitmap.Width, bitmap.Height, paint);

                            paint.Color = Color.White;
                            var textWidth = paint.MeasureText(program.Title);

                            // 回転する
                            // canvas.Rotate(45);
                            //canvas.DrawText(program.Title, 0, 0, paint);

                            // 
                            // canvas.DrawText(program.Title, (bitmap.Width / 2) - (textWidth / 2), (bitmap.Height / 2) + (paint.TextSize / 2), paint);

                            // 折り返しつつ描画
                            var margin = 16;
                            var textLayout = new StaticLayout(program.Title, textPaint, canvas.Width - (margin * 2), Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
                            canvas.Translate(margin, (canvas.Height / 2) - (textLayout.Height / 2));
                            textLayout.Draw(canvas);

                            canvas.Restore();
                        }
                        builder.SetLargeIcon(bitmap);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(Tag, ex.ToString());
                }

                this._notificationManager.Notify(program.Start.Ticks.GetHashCode(), builderBigPicture.Build());
            }
        }
Exemplo n.º 16
0
        public static Bitmap DrawTextImage(Bitmap image, string text, string author)
        {
            var resultimage = image;
            
            Bitmap.Config bitmapconfig = image.GetConfig();

            System.Diagnostics.Debug.WriteLine("kích thước ảnh: " + image.Width + " " + image.Height);
            if (bitmapconfig == null)
            {
                bitmapconfig = Bitmap.Config.Argb8888;
            }

            Bitmap bg_bitmap = Bitmap.CreateBitmap(image.Width, image.Height + image.Width / 5, Bitmap.Config.Argb8888);

            image = image.Copy(bitmapconfig, true);
            var image1 = image;
            Canvas bgcanvas = new Canvas(bg_bitmap);
            Paint p = new Paint();
            p.Color = Android.Graphics.Color.White;

            TextPaint paint = new TextPaint(PaintFlags.AntiAlias);
            TextPaint paint_author = new TextPaint(PaintFlags.AntiAlias);

            Rect bounds = new Rect();
            paint.Color = Android.Graphics.Color.White;
            paint.TextSize = 150;
            paint.SetTypeface(Typeface.Create(Typeface.Default, TypefaceStyle.Bold));

            paint_author.Color = Android.Graphics.Color.Black;
            paint_author.TextSize = 120;
            
            System.Diagnostics.Debug.WriteLine("kích thước ảnh: " + image.Width + " " + image.Height);
            int textWidth = bgcanvas.Width - 200;
            int textHeight = 0;
            StaticLayout textLayout = new StaticLayout(text, paint, textWidth, Android.Text.Layout.Alignment.AlignCenter, 1, 0, false);
            textHeight = textLayout.Height;
            while (textHeight > image.Height - 200)
            {
                paint.TextSize = paint.TextSize - 1;
                textLayout = new StaticLayout(text, paint, textWidth, Android.Text.Layout.Alignment.AlignCenter, 1, 0, false);
                textHeight = textLayout.Height;
            };
            
            //StaticLayout textLayout = new StaticLayout(text, paint, textWidth, Android.Text.Layout.Alignment.AlignCenter, 1, 0, false);

            StaticLayout textLayout_author = new StaticLayout(author, paint_author, textWidth, Android.Text.Layout.Alignment.AlignCenter, 1, 0, false);

            //textHeight = textLayout.Height;

            int textHeight_author = textLayout_author.Height;

            float x = (image.Width - textWidth) / 2;
            float y = (image.Height - textHeight) / 2;

            float x_author = (image.Width - textWidth) / 2;
            float y_author = image.Height + (image.Width / 5 - textHeight_author) / 2;

            //draw background + image
            bgcanvas.DrawColor(Android.Graphics.Color.White);
            bgcanvas.DrawBitmap(bg_bitmap, 0, 0, p);
            bgcanvas.DrawBitmap(image, 0, 0, null);
            //write content
            bgcanvas.Save();
            bgcanvas.Translate(x, y);
            textLayout.Draw(bgcanvas);
            bgcanvas.Restore();
            //write author
            bgcanvas.Save();
            bgcanvas.Translate(x_author, y_author);
            textLayout_author.Draw(bgcanvas);
            bgcanvas.Restore();

            return bg_bitmap;
        }
Exemplo n.º 17
0
#pragma warning disable IDE0060 // Remove unused parameter
        internal static StaticLayout Truncate(string text, Forms9Patch.F9PFormattedString baseFormattedString, TextPaint paint, int availWidth, int availHeight, AutoFit fit, LineBreakMode lineBreakMode, float lineHeightMultiplier, ref int lines, ref ICharSequence textFormatted)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            StaticLayout layout         = null;
            var          fontMetrics    = paint.GetFontMetrics();
            var          fontLineHeight = fontMetrics.Descent - fontMetrics.Ascent;
            var          fontLeading    = System.Math.Abs(fontMetrics.Bottom - fontMetrics.Descent);

            textFormatted = ((ICharSequence)baseFormattedString?.ToSpannableString()) ?? new Java.Lang.String(text);
            if (lines > 0)
            {
                if (baseFormattedString != null)
                {
                    layout = TextExtensions.StaticLayout(textFormatted, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, lineHeightMultiplier, 0.0f, true);

                    if (layout.Height > availHeight)
                    {
                        var visibleLines = (int)((fontLeading + availHeight) / (fontLineHeight + fontLeading));
                        if (visibleLines < lines)
                        {
                            lines = visibleLines;
                        }
                    }
                    if (layout.LineCount > lines && lines > 0)
                    {
                        var secondToLastEnd = lines > 1 ? layout.GetLineEnd(lines - 2) : 0;
                        var start           = lines > 1 ? layout.GetLineStart(layout.LineCount - 2) : 0;
                        textFormatted?.Dispose();
                        switch (lineBreakMode)
                        {
                        case LineBreakMode.HeadTruncation:
                            textFormatted = StartTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, start, layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        case LineBreakMode.MiddleTruncation:
                            textFormatted = MidTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), (layout.GetLineEnd(lines - 1) + layout.GetLineStart(lines - 1)) / 2 - 1, start, layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        case LineBreakMode.TailTruncation:
                            textFormatted = EndTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        default:
                            textFormatted = TruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;
                        }
                    }
                }
                else
                {
                    layout = TextExtensions.StaticLayout(text, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, lineHeightMultiplier, 0.0f, true);
                    if (layout.Height > availHeight)
                    {
                        var visibleLines = (int)((fontLeading + availHeight) / (fontLineHeight + fontLeading));
                        if (visibleLines < lines)
                        {
                            lines = visibleLines;
                        }
                    }
                    if (layout.LineCount > lines && lines > 0)
                    {
                        var secondToLastEnd = lines > 1 ? layout.GetLineEnd(lines - 2) : 0;
                        var start           = lines > 1 ? layout.GetLineStart(layout.LineCount - 2) : 0;
                        switch (lineBreakMode)
                        {
                        case LineBreakMode.HeadTruncation:
                            text = StartTruncatedLastLine(text, paint, secondToLastEnd, start, layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        case LineBreakMode.MiddleTruncation:
                            text = MidTruncatedLastLine(text, paint, secondToLastEnd, layout.GetLineStart(lines - 1), (layout.GetLineEnd(lines - 1) + layout.GetLineStart(lines - 1)) / 2 - 1, start, layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        case LineBreakMode.TailTruncation:
                            text = EndTruncatedLastLine(text, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth, lineHeightMultiplier);
                            break;

                        default:
                            text = text.Substring(0, layout.GetLineEnd(lines - 1));
                            break;
                        }
                        textFormatted?.Dispose();
                        textFormatted = new Java.Lang.String(text);
                    }
                }
            }
            var result = TextExtensions.StaticLayout(textFormatted, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, lineHeightMultiplier, 0.0f, true);

            layout?.Dispose();
            //textFormatted?.Dispose();  // this causes Bc3.Keypad to break!
            return(result);
        }
Exemplo n.º 18
0
        private Rect GetTextSize(Java.Lang.String text, TextPaint textPaint, float textSize)
        {
            textPaint.TextSize = textSize;
            var layout = new StaticLayout (text, textPaint, Integer.MaxValue, Layout.Alignment.AlignNormal, 1f, 0f, true);
            var textWidth = 0;
            var lines = text.Split (Java.Lang.JavaSystem.GetProperty ("line.separator"));
            for (var i = 0; i < lines.Length; ++i)
                textWidth = System.Math.Max (textWidth, MeasureTextWidth (textPaint, lines [i]));

            return new Rect (0, 0, textWidth, layout.Height);
        }
Exemplo n.º 19
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

//            var display = Game.Activity.WindowManager.DefaultDisplay;
//            var metrics = new DisplayMetrics();
//            display.GetMetrics(metrics);

            // Do not take into account ScaleDensity for now.
//            var fontScaleFactor = metrics.ScaledDensity;
//            textDef.FontSize = (int)(textDef.FontSize * fontScaleFactor);


            // out paint object to hold our drawn text
//            var paintFlags = new PaintFlags();
//            if (textDefinition.isShouldAntialias)
//                paintFlags = PaintFlags.AntiAlias | PaintFlags.SubpixelText;

            var textPaint = new TextPaint();

            textPaint.Color     = Android.Graphics.Color.White;
            textPaint.TextAlign = Paint.Align.Left;
            textPaint.AntiAlias = textDefinition.isShouldAntialias;

            textPaint.TextSize = textDef.FontSize;

            var fontName = textDef.FontName;
            var ext      = System.IO.Path.GetExtension(fontName);

            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                CCContentManager.SharedContentManager.GetAssetStreamAsBytes(fontName, out fontName);

                var activity = Android.App.Application.Context;

                try
                {
                    var typeface = Typeface.CreateFromAsset(activity.Assets, fontName);
                    textPaint.SetTypeface(typeface);
                }
                catch (Exception)
                {
                    textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
                }
            }
            else
            {
                textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
            }

            // color
            var foregroundColor = Android.Graphics.Color.White;

            textPaint.Color = foregroundColor;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? Layout.Alignment.AlignOpposite
                : (CCTextAlignment.Center == horizontalAlignment) ? Layout.Alignment.AlignCenter
                : Layout.Alignment.AlignNormal;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }


            // Get bounding rectangle - we need its attribute and method values
            var layout = new StaticLayout(text, textPaint,
                                          (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);

            var boundingRect = new Rect();
            var lineBounds   = new Rect();

            // Loop through all the lines so we can find our drawing offsets
            var lineCount = layout.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
            {
                return(new CCTexture2D());
            }

            for (int lc = 0; lc < lineCount; lc++)
            {
                layout.GetLineBounds(lc, lineBounds);
                var max = (int)Math.Ceiling(layout.GetLineMax(lc));

                if (boundingRect.Right < max)
                {
                    boundingRect.Right = max;
                }

                boundingRect.Bottom = lineBounds.Bottom;
            }

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Right;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Bottom;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != Layout.Alignment.AlignNormal)
            {
                layout = new StaticLayout(text, textPaint,
                                          (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);
            }


            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                      // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                                  // align to center

            try {
                // Create our platform dependant image to be drawn to.
                using (Bitmap textureBitmap = Bitmap.CreateBitmap(imageWidth, imageHeight, Bitmap.Config.Argb8888))
                {
                    using (Canvas drawingCanvas = new Canvas(textureBitmap))
                    {
                        drawingCanvas.DrawARGB(0, 255, 255, 255);

                        // Set our vertical alignment
                        drawingCanvas.Translate(0, yOffset);

                        // Now draw the text using our layout
                        layout.Draw(drawingCanvas);

                        // Create a pixel array
                        int[] pixels = new int[imageWidth * imageHeight];

                        // Now lets get our pixels.
                        // We use CopyPixelsToBuffer so that it is in Premultiplied Alpha already.
                        // Using Bitmap.GetPixels return non Premultiplied Alpha which causes blending problems
                        Java.Nio.IntBuffer byteBuffer = Java.Nio.IntBuffer.Allocate(imageWidth * imageHeight);
                        textureBitmap.CopyPixelsToBuffer(byteBuffer);
                        if (byteBuffer.HasArray)
                        {
                            byteBuffer.Rewind();
                            byteBuffer.Get(pixels, 0, pixels.Length);
                        }

                        // Make sure we recycle - Let's keep it green
                        textureBitmap.Recycle();

                        // Here we create our Texture and then set our pixel data.
                        var texture = new CCTexture2D(imageWidth, imageHeight);
                        texture.XNATexture.SetData <int>(pixels);

                        return(texture);
                    }
                }
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel Android: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace);
                return(new CCTexture2D());
            }
        }
Exemplo n.º 20
0
 private static void DrawTime(Canvas canvas, StaticLayout timeLayout)
 {
     timeLayout.Draw(canvas);
 }
Exemplo n.º 21
0
        /// <summary>
        /// Calculates and returns an appropriate width and height value for the contents of the control.
        /// This is called by the underlying grid layout system and should not be used in application logic.
        /// </summary>
        /// <param name="constraints">The size that the control is limited to.</param>
        /// <returns>The label size, given a width constraint and a measured height.</returns>
        public Size Measure(Size constraints)
        {
            if (string.IsNullOrEmpty(StringValue))
            {
                return(new Size());
            }

            if (_constraints == constraints)
            {
                return(new Size(MeasuredWidth, MeasuredHeight));
            }

            _constraints = constraints;
            var height        = _constraints.Height > int.MaxValue ? int.MaxValue : (int)Math.Ceiling(_constraints.Height);
            var width         = _constraints.Width > int.MaxValue ? int.MaxValue : (int)Math.Ceiling(_constraints.Width);
            var measuredWidth = 0;

            // Do not resize if the view does not have dimensions or there is no text
            if (string.IsNullOrEmpty(StringValue) || height <= 0 || width <= 0 || TextSize <= 0)
            {
                if (Text != string.Empty)
                {
                    SetText(string.Empty, BufferType.Normal);
                }
                _measuredLines = 0;
            }
            else
            {
                // modified: make a copy of the original TextPaint object for measuring
                // (apparently the object gets modified while measuring, see also the
                // docs for TextView.getPaint() (which states to access it read-only)
                var paint = new TextPaint(Paint)
                {
                    TextSize = TextSize,
                };
                // Measure using a static layout
                var layout = new StaticLayout(StringValue, paint, width, Layout.Alignment.AlignNormal, 1.0f, 0, true);

                float totalWidth = 0;

                // If we had reached our minimum text size and still don't fit, append an ellipsis
                if (layout.Height > height || _maxLineCount > 0 && layout.LineCount > _maxLineCount)
                {
                    var ellipsisWidth = Paint.MeasureText(Ellipsis);
                    var addEllipsis   = false;
                    int lastLineIndex;

                    if (height == int.MaxValue)
                    {
                        lastLineIndex = Math.Max(layout.LineCount - 1, 0);
                    }
                    else
                    {
                        lastLineIndex = Math.Max(layout.GetLineForVertical(height) - 1, 0);
                        if (lastLineIndex < layout.LineCount - 1)
                        {
                            addEllipsis = true;
                        }
                    }

                    if (_maxLineCount > 0 && lastLineIndex > _maxLineCount - 1)
                    {
                        lastLineIndex = _maxLineCount - 1;
                        addEllipsis   = true;
                    }

                    _measuredLines = lastLineIndex + 1;
                    var ellipsizeIndex     = layout.GetLineEnd(lastLineIndex);
                    var lastLineStartIndex = layout.GetLineStart(lastLineIndex);
                    ellipsizeIndex = lastLineStartIndex + (int)Math.Ceiling((ellipsizeIndex - lastLineStartIndex) * 1.4);
                    if (StringValue.Length < ellipsizeIndex)
                    {
                        ellipsizeIndex = StringValue.Length;
                        addEllipsis    = false;
                    }
                    var text = StringValue.Substring(lastLineStartIndex, ellipsizeIndex - lastLineStartIndex).TrimEnd();
                    totalWidth = Paint.MeasureText(text) + (addEllipsis ? ellipsisWidth : 0);

                    // Trim characters off until we have enough room to draw the ellipsis
                    while (width < totalWidth && text != string.Empty)
                    {
                        addEllipsis = true;
                        text        = StringValue.Substring(lastLineStartIndex, --ellipsizeIndex - lastLineStartIndex);
                        totalWidth  = Paint.MeasureText(text) + ellipsisWidth;
                    }

                    if (addEllipsis)
                    {
                        text = StringValue.Substring(0, ellipsizeIndex).TrimEnd() + Ellipsis;
                        if (text != Text)
                        {
                            SetText(text, BufferType.Normal);
                        }
                    }
                }
                else if (base.Text != StringValue)
                {
                    SetText(StringValue, BufferType.Normal);
                    _measuredLines = layout.LineCount;
                }
                else
                {
                    _measuredLines = layout.LineCount;
                }

                // Some devices try to auto adjust line spacing, so force default line spacing
                // and invalidate the layout as a side effect
                SetLineSpacing(0, 1.0f);

                for (var i = 0; i < _measuredLines; i++)
                {
                    var lineWidth = layout.GetLineWidth(i);
                    if (lineWidth > totalWidth)
                    {
                        totalWidth = lineWidth;
                    }
                }
                measuredWidth = (int)Math.Ceiling(totalWidth);
            }

            var size = this.MeasureView(constraints);

            return(new Size(measuredWidth, size.Height));
        }
Exemplo n.º 22
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= (int)contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            var display = Game.Activity.WindowManager.DefaultDisplay;
            var metrics = new DisplayMetrics();

            display.GetMetrics(metrics);

            // Do not take into account ScaleDensity for now.
//            var fontScaleFactor = metrics.ScaledDensity;
//            textDef.FontSize = (int)(textDef.FontSize * fontScaleFactor);


            // out paint object to hold our drawn text
            var textPaint = new TextPaint(PaintFlags.AntiAlias);

            textPaint.Color     = Android.Graphics.Color.White;
            textPaint.TextAlign = Paint.Align.Left;

            textPaint.TextSize = textDef.FontSize;

            var fontName = textDef.FontName;
            var ext      = System.IO.Path.GetExtension(fontName);

            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                var path     = System.IO.Path.Combine(CCContentManager.SharedContentManager.RootDirectory, fontName);
                var activity = Game.Activity;

                try
                {
                    var typeface = Typeface.CreateFromAsset(activity.Assets, path);
                    textPaint.SetTypeface(typeface);
                }
                catch (Exception)
                {
                    textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
                }
            }
            else
            {
                textPaint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal));
            }

            // color
            var fontColor       = textDef.FontFillColor;
            var fontAlpha       = textDef.FontAlpha;
            var foregroundColor = new Android.Graphics.Color(fontColor.R,
                                                             fontColor.G,
                                                             fontColor.B,
                                                             fontAlpha);

            textPaint.Color = foregroundColor;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? Layout.Alignment.AlignOpposite
                : (CCTextAlignment.Center == horizontalAlignment) ? Layout.Alignment.AlignCenter
                : Layout.Alignment.AlignNormal;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }


            // Get bounding rectangle - we need its attribute and method values
            var layout = new StaticLayout(text, textPaint,
                                          (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);

            var boundingRect = new Rect();
            var lineBounds   = new Rect();

            // Loop through all the lines so we can find our drawing offsets
            var lineCount = layout.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
            {
                return(new CCTexture2D());
            }

            for (int lc = 0; lc < lineCount; lc++)
            {
                layout.GetLineBounds(lc, lineBounds);
                var max = layout.GetLineMax(lc);

                if (boundingRect.Right < max)
                {
                    boundingRect.Right = (int)max;
                }

                boundingRect.Bottom = lineBounds.Bottom;
            }

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Right;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Bottom;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != Layout.Alignment.AlignNormal)
            {
                layout = new StaticLayout(text, textPaint,
                                          (int)dimensions.Width, textAlign, 1.0f, 0.0f, false);
            }


            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                      // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                                  // align to center

            // Create our platform dependant image to be drawn to.
            var textureBitmap = Bitmap.CreateBitmap(imageWidth, imageHeight, Bitmap.Config.Argb8888);
            var drawingCanvas = new Canvas(textureBitmap);

            // Set our vertical alignment
            drawingCanvas.Translate(0, yOffset);

            // Now draw the text using our layout
            layout.Draw(drawingCanvas);

            // We will use Texture2D from stream here instead of CCTexture2D stream.
            var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, textureBitmap);

            // Create our texture of the label string.
            var texture = new CCTexture2D(tex);

            return(texture);
        }
Exemplo n.º 23
0
		public void resizeText(int width, int height) {
			string text = this.Text;
			// Do not resize if the view does not have dimensions or there is no text
			if (text == null || text.Length == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
				return;
			}

			// Get the text view's paint object
			TextPaint textPaint = this.Paint;

			// Store the current text size
			float oldTextSize = textPaint.TextSize;
			// If there is a max text size set, use the lesser of that and the default text size
			float targetTextSize = mMaxTextSize > 0 ? Java.Lang.Math.Min(mTextSize, mMaxTextSize) : mTextSize;

			// Get the required text height
			int textHeight =  getTextHeight(text, textPaint, width, targetTextSize);

			// Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
			while (textHeight > height && targetTextSize > mMinTextSize) {
				targetTextSize = Java.Lang.Math.Max(targetTextSize - 2, mMinTextSize);
				textHeight = getTextHeight(text, textPaint, width, targetTextSize);
			}

			// If we had reached our minimum text size and still don't fit, append an ellipsis
			if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
				// Draw using a static layout
				// modified: use a copy of TextPaint for measuring
				TextPaint paint = new TextPaint(textPaint);
				// Draw using a static layout
				StaticLayout layout = new StaticLayout(text, paint, width, Android.Text.Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
				// Check that we have a least one line of rendered text
				if (layout.LineCount > 0) {
					// Since the line at the specific vertical position would be cut off,
					// we must trim up to the previous line
					int lastLine = layout.GetLineForVertical(height) - 1;
					// If the text would not even fit on a single line, clear it
					if (lastLine < 0) {
						this.Text = "";
					}
					// Otherwise, trim to the previous line and add an ellipsis
					else {
						int start = layout.GetLineStart(lastLine);
						int end = layout.GetLineEnd(lastLine);
						float lineWidth = layout.GetLineWidth(lastLine);
						float ellipseWidth = textPaint.MeasureText(mEllipsis);

						// Trim characters off until we have enough room to draw the ellipsis
						while (width < lineWidth + ellipseWidth) {
							lineWidth = textPaint.MeasureText(text.Substring(start, --end + 1).ToString());
						}
						this.Text = text.Substring(0, end) + mEllipsis;
					}
				}
			}

			// Some devices try to auto adjust line spacing, so force default line spacing
			// and invalidate the layout as a side effect
			this.SetTextSize(ComplexUnitType.Px, targetTextSize);
			this.SetLineSpacing(mSpacingAdd, mSpacingMult);

			// Notify the listener if registered
			if (mTextResizeListener != null) {
				mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
			}

			// Reset force resize flag
			mNeedsResize = false;
		}
Exemplo n.º 24
0
		private void drawString(Canvas gfx, TextPaint paint, float x, float y)
		{
			if (_maxWidth == int.MaxValue)
			{
				gfx.DrawText(_text, x, y, paint);
			}
			else
			{
				paint.TextAlign = alignWrap();
				StaticLayout layout = new StaticLayout (_text, paint, _maxWidth, Layout.Alignment.AlignNormal, 1f, 0f, false);
				gfx.Translate(x, y);
				layout.Draw(gfx);
				gfx.Translate(-x, -y);
			}
		}
Exemplo n.º 25
0
		private int getTextHeight(string source, TextPaint paint, int width, float textSize) {
			// modified: make a copy of the original TextPaint object for measuring
			// (apparently the object gets modified while measuring, see also the
			// docs for TextView.getPaint() (which states to access it read-only)
			TextPaint paintCopy = new TextPaint(paint);
			// Update the text paint object
			paintCopy.TextSize = textSize;
			// Measure using a static layout
			StaticLayout layout = new StaticLayout(source, paintCopy, width, Android.Text.Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, true);
			return layout.Height;
		}
Exemplo n.º 26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var metrics = new DisplayMetrics();

            WindowManager.DefaultDisplay.GetMetrics(metrics);

            float spacing = 40;

            var root = new LayoutItem(this)
            {
                Width         = metrics.WidthPixels,
                Height        = metrics.HeightPixels,
                PaddingBottom = 80
            };

            var label = new Item <TextView>(this)
            {
                Margin = spacing
            };

            label.View.Text  = "This is the list of items you have added. You can add new items and clear the list using the buttons at the bottom. This label has extra lines on purpose.";
            label.SelfSizing = delegate(Xamarin.Flex.Item item, ref float width, ref float height)
            {
                height = new StaticLayout(label.View.Text, label.View.Paint, (int)width, Layout.Alignment.AlignNormal, 1, 0, true).Height;
            };
            root.Add(label);

            var list = new Item <ListView>(this)
            {
                Grow        = 1,
                MarginLeft  = spacing,
                MarginRight = spacing
            };

            list.View.Adapter = new ArrayAdapter(this, Resource.Layout.TextViewItem);
            root.Add(list);

            var input = new Item <EditText>(this)
            {
                Margin = spacing
            };

            input.View.Hint = "Enter list item";
            input.Height    = 80;
            root.Add(input);

            var buttons_row = new LayoutItem(this)
            {
                Direction    = Xamarin.Flex.Direction.Row,
                Height       = 80,
                MarginLeft   = spacing,
                MarginRight  = spacing,
                MarginBottom = spacing
            };

            root.Add(buttons_row);

            var add_button = new Item <Button>(this)
            {
                Grow   = 1,
                Height = 80
            };

            add_button.View.Text   = "Add";
            add_button.View.Click += delegate
            {
                var adapter = (ArrayAdapter)list.View.Adapter;
                if (input.View.Text != "")
                {
                    adapter.Add(input.View.Text);
                    input.View.Text = "";
                }
            };
            buttons_row.Add(add_button);

            var clear_button = new Item <Button>(this)
            {
                Grow   = 1,
                Height = 80
            };

            clear_button.View.Text   = "Clear";
            clear_button.View.Click += delegate
            {
                var adapter = (ArrayAdapter)list.View.Adapter;
                adapter.Clear();
            };
            buttons_row.Add(clear_button);

            root.Layout();

            SetContentView(root.view);
        }
Exemplo n.º 27
0
        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            try
            {
                if (Build.VERSION.SdkInt >= (BuildVersionCodes)16)
                {
                    StaticLayout layout = null !;
                    Field        field  = null !;

                    Class klass = Class.FromType(typeof(DynamicLayout));

                    try
                    {
                        Field insetsDirtyField = klass.GetDeclaredField("sStaticLayout");

                        insetsDirtyField.Accessible = (true);
                        layout = (StaticLayout)insetsDirtyField.Get(klass);
                    }
                    catch (NoSuchFieldException ex)
                    {
                        Methods.DisplayReportResultTrack(ex);
                    }
                    catch (IllegalAccessException ex)
                    {
                        Methods.DisplayReportResultTrack(ex);
                    }

                    if (layout != null)
                    {
                        try
                        {
                            //Field insetsDirtyField = klass.GetDeclaredField("sStaticLayout");

                            field            = layout.Class.GetDeclaredField("mMaximumVisibleLineCount");
                            field.Accessible = (true);
                            field.SetInt(layout, MaxLines);
                        }
                        catch (NoSuchFieldException e)
                        {
                            Methods.DisplayReportResultTrack(e);
                        }
                        catch (IllegalAccessException e)
                        {
                            Methods.DisplayReportResultTrack(e);
                        }
                    }

                    base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

                    if (layout != null && field != null)
                    {
                        try
                        {
                            field.SetInt(layout, Integer.MaxValue);
                        }
                        catch (IllegalAccessException e)
                        {
                            Methods.DisplayReportResultTrack(e);
                        }
                    }
                }
                else
                {
                    base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
                }
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
Exemplo n.º 28
0
        // Resize the text size with specified width and height
        public void ResizeText(int width, int height)
        {
            string text = Text;
            // Do not resize if the view does not have dimensions or there is no text
            if (string.IsNullOrEmpty(text) || height <= 0 || width <= 0 || _textSize == 0)
                return;
            // Get the text view's paint object
            TextPaint textPaint = Paint;
            // Store the current text size
            float oldTextSize = textPaint.TextSize;
            // If there is a max text size set, use the lesser of that and the default text size
            float targetTextSize = _maxTextSize > 0 ? Math.Min(_textSize, _maxTextSize) : _textSize;

            // Get the required text height
            int textHeight = GetTextHeight(text, textPaint, width, targetTextSize);
            int textWidth = GetTextWidth(text, textPaint, width, targetTextSize);

            // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
            while (((textHeight > height) || (textWidth > width)) && targetTextSize > _minTextSize)
            {
                targetTextSize = Math.Max(targetTextSize - 2, _minTextSize);
                textHeight = GetTextHeight(text, textPaint, width, targetTextSize);
                textWidth = GetTextWidth(text, textPaint, width, targetTextSize);
            }

            // If we had reached our minimum text size and still don't fit, append an ellipsis
            if (_addEllipsis && targetTextSize == _minTextSize && textHeight > height)
            {
                // Draw using a static layout
                StaticLayout layout = new StaticLayout(text, textPaint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, false);
                // Check that we have a least one line of rendered text
                if (layout.LineCount > 0)
                {
                    // Since the line at the specific vertical position would be cut off,
                    // we must trim up to the previous line
                    int lastLine = layout.GetLineForVertical(height) - 1;
                    // If the text would not even fit on a single line, clear it
                    if (lastLine < 0)
                    {
                        Text = "";
                    }
                    // Otherwise, trim to the previous line and add an ellipsis
                    else
                    {
                        int start = layout.GetLineStart(lastLine);
                        int end = layout.GetLineEnd(lastLine);
                        float lineWidth = layout.GetLineWidth(lastLine);
                        float ellipseWidth = textPaint.MeasureText(Ellipsis);

                        // Trim characters off until we have enough room to draw the ellipsis
                        while (width < lineWidth + ellipseWidth)
                        {
                            lineWidth = textPaint.MeasureText(text.Substring(start, --end + 1));
                        }
                        Text = (text.Substring(0, end) + Ellipsis);
                    }
                }
            }

            // Some devices try to auto adjust line spacing, so force default line spacing
            // and invalidate the layout as a side effect
            textPaint.TextSize = targetTextSize;
            SetLineSpacing(_spacingAdd, _spacingMult);

            TextResized?.Invoke(this, new TextResizedEventArgs
            {
                OldSize = oldTextSize,
                NewSize = targetTextSize
            });

            // Reset force resize flag
            _needsResize = false;
        }
        public override Carto.Graphics.Bitmap OnDrawPopup(PopupDrawInfo popupDrawInfo)
        {
            PopupStyle style = popupDrawInfo.Popup.Style;

            // Calculate scaled dimensions
            float DPToPX = popupDrawInfo.DPToPX;
            float PXTODP = 1 / DPToPX;

            if (style.ScaleWithDPI)
            {
                DPToPX = 1;
            }
            else
            {
                PXTODP = 1;
            }

            float screenWidth = popupDrawInfo.ScreenBounds.GetWidth() * PXTODP;
            float screenHeight = popupDrawInfo.ScreenBounds.GetHeight() * PXTODP;

            // Update sizes based on scale (uses extension method, cf. Shared/Extensions
            int fontSize = FontSize.Update(DPToPX);

            int triangleWidth = TriangleSize.Update(DPToPX);
            int triangleHeight = TriangleSize.Update(DPToPX);

            int strokeWidth = StrokeWidth.Update(DPToPX);
            int screenPadding = ScreenPadding.Update(DPToPX);

            // Set font
            var font = Android.Graphics.Typeface.Create("HelveticaNeue-Light", Android.Graphics.TypefaceStyle.Normal);

            // Calculate the maximum popup size, adjust with dpi
            int maxPopupWidth = (int)(Math.Min(screenWidth, screenHeight));

            float halfStrokeWidth = strokeWidth * 0.5f;
            int maxTextWidth = maxPopupWidth - (2 * screenPadding + strokeWidth);

            // Measure text
            TextPaint textPaint = new TextPaint { Color = TextColor, TextSize = fontSize };
            textPaint.SetTypeface(font);

            var textLayout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.AlignNormal, 1, 0, false);

            int textX = (int)Math.Min(textPaint.MeasureText(text), textLayout.Width);
            int textY = textLayout.Height;

            int popupWidth = textX + (2 * PopupPadding + strokeWidth + triangleWidth);
            int popupHeight = textY + (2 * PopupPadding + strokeWidth);

            var bitmap = Android.Graphics.Bitmap.CreateBitmap(popupWidth, popupHeight, Android.Graphics.Bitmap.Config.Argb8888);
            var canvas = new Android.Graphics.Canvas(bitmap);

            var trianglePath = new Android.Graphics.Path();
            trianglePath.MoveTo(triangleWidth, 0);
            trianglePath.LineTo(halfStrokeWidth, triangleHeight * 0.5f);
            trianglePath.LineTo(triangleWidth, triangleHeight);
            trianglePath.Close();

            int triangleOffsetX = 0;
            int triangleOffsetY = (popupHeight - triangleHeight) / 2;

            // Create paint object
            var paint = new Android.Graphics.Paint();
            paint.AntiAlias = true;
            paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            paint.StrokeWidth = strokeWidth;
            paint.Color = StrokeColor;

            // Stroke background
            var background = new Android.Graphics.RectF();
            background.Left = triangleWidth;
            background.Top = halfStrokeWidth;
            background.Right = popupWidth - strokeWidth;
            background.Bottom = popupHeight - strokeWidth;
            canvas.DrawRect(background, paint);

            // Stroke triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            // Fill background
            paint.SetStyle(Android.Graphics.Paint.Style.Fill);
            paint.Color = BackgroundColor;
            canvas.DrawRect(background, paint);

            // Fill triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            if (textLayout != null)
            {
                // Draw text
                canvas.Save();
                canvas.Translate(halfStrokeWidth + triangleWidth + PopupPadding, halfStrokeWidth + PopupPadding);
                textLayout.Draw(canvas);
                canvas.Restore();
            }

            return BitmapUtils.CreateBitmapFromAndroidBitmap(bitmap);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Gets the size of the desired.
        /// </summary>
        /// <returns>The desired size.</returns>
        /// <param name="widthConstraint">Width constraint.</param>
        /// <param name="heightConstraint">Height constraint.</param>
        public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
        {
            if (_currentControlState.IsNullOrEmpty || Control == null)
            {
                return(new SizeRequest(Xamarin.Forms.Size.Zero));
            }

            _currentControlState.AvailWidth = MeasureSpec.GetSize(widthConstraint);
            if (MeasureSpec.GetMode(widthConstraint) == Android.Views.MeasureSpecMode.Unspecified)
            {
                _currentControlState.AvailWidth = int.MaxValue / 2;
            }
            _currentControlState.AvailHeight = MeasureSpec.GetSize(heightConstraint);
            if (MeasureSpec.GetMode(heightConstraint) == Android.Views.MeasureSpecMode.Unspecified)
            {
                _currentControlState.AvailHeight = int.MaxValue / 2;
            }

            if (_currentControlState.AvailWidth <= 0 || _currentControlState.AvailHeight <= 0)
            {
                return(new SizeRequest(Xamarin.Forms.Size.Zero));
            }

            if (_currentControlState == _lastControlState && _lastSizeRequest.HasValue)
            {
                return(_lastSizeRequest.Value);
            }



            ICharSequence text        = _currentControlState.JavaText;
            var           tmpFontSize = BoundTextSize(Element.FontSize);

            Control.TextSize = tmpFontSize;
            Control.SetSingleLine(false);
            Control.SetMaxLines(int.MaxValue / 2);
            Control.SetIncludeFontPadding(false);
            Control.Ellipsize = null;

            int tmpHt = -1;
            int tmpWd = -1;

            var fontMetrics    = Control.Paint.GetFontMetrics();
            var fontLineHeight = fontMetrics.Descent - fontMetrics.Ascent;
            var fontLeading    = System.Math.Abs(fontMetrics.Bottom - fontMetrics.Descent);

            if (DebugCondition)
            {
                System.Diagnostics.Debug.WriteLine("");
            }

            if (_currentControlState.Lines == 0)
            {
                if (_currentControlState.AvailHeight < int.MaxValue / 3)
                {
                    tmpFontSize = F9PTextView.ZeroLinesFit(_currentControlState.JavaText, new TextPaint(Control.Paint), ModelMinFontSize, tmpFontSize, _currentControlState.AvailWidth, _currentControlState.AvailHeight);
                }
            }
            else
            {
                if (_currentControlState.AutoFit == AutoFit.Lines)
                {
                    if (_currentControlState.AvailHeight > int.MaxValue / 3)
                    {
                        tmpHt = (int)System.Math.Round(_currentControlState.Lines * fontLineHeight + (_currentControlState.Lines - 1) * fontLeading);
                    }
                    else
                    {
                        var fontPointSize   = tmpFontSize;
                        var lineHeightRatio = fontLineHeight / fontPointSize;
                        var leadingRatio    = fontLeading / fontPointSize;
                        tmpFontSize = ((_currentControlState.AvailHeight / (_currentControlState.Lines + leadingRatio * (_currentControlState.Lines - 1))) / lineHeightRatio - 0.1f);
                    }
                }
                else if (_currentControlState.AutoFit == AutoFit.Width)
                {
                    tmpFontSize = F9PTextView.WidthFit(_currentControlState.JavaText, new TextPaint(Control.Paint), _currentControlState.Lines, ModelMinFontSize, tmpFontSize, _currentControlState.AvailWidth, _currentControlState.AvailHeight);
                }
            }

            /*
             * if (_currentControlState.Lines == 0) // && _currentControlState.AutoFit != AutoFit.None)
             *  tmpFontSize = F9PTextView.ZeroLinesFit(_currentControlState.JavaText, new TextPaint(Control.Paint), ModelMinFontSize, tmpFontSize, _currentControlState.AvailWidth, _currentControlState.AvailHeight);
             * else if (_currentControlState.AutoFit == AutoFit.Lines)
             * {
             *
             *  if (_currentControlState.AvailHeight > int.MaxValue / 3)
             *      tmpHt = (int)System.Math.Round(_currentControlState.Lines * fontLineHeight + (_currentControlState.Lines - 1) * fontLeading);
             *  else
             *  {
             *      var fontPointSize = tmpFontSize;
             *      var lineHeightRatio = fontLineHeight / fontPointSize;
             *      var leadingRatio = fontLeading / fontPointSize;
             *      tmpFontSize = ((_currentControlState.AvailHeight / (_currentControlState.Lines + leadingRatio * (_currentControlState.Lines - 1))) / lineHeightRatio - 0.1f);
             *  }
             * }
             * else if (_currentControlState.AutoFit == AutoFit.Width)
             *  tmpFontSize = F9PTextView.WidthFit(_currentControlState.JavaText, new TextPaint(Control.Paint), _currentControlState.Lines, ModelMinFontSize, tmpFontSize, _currentControlState.AvailWidth, _currentControlState.AvailHeight);
             */

            tmpFontSize = BoundTextSize(tmpFontSize);

            // this is the optimal font size.  Let it be known!
            if (tmpFontSize != Element.FittedFontSize)
            {
                //Device.StartTimer(TimeSpan.FromMilliseconds(50), () =>
                //{
                if (Element != null && Control != null)  // multipicker test was getting here with Element and Control both null
                {
                    if (tmpFontSize == Element.FontSize || (Element.FontSize == -1 && tmpFontSize == F9PTextView.DefaultTextSize))
                    {
                        Element.FittedFontSize = -1;
                    }
                    else
                    {
                        Element.FittedFontSize = tmpFontSize;
                    }
                }
                //    return false;
                //});
            }


            var syncFontSize = (float)((ILabel)Element).SynchronizedFontSize;

            if (syncFontSize >= 0 && tmpFontSize != syncFontSize)
            {
                tmpFontSize = syncFontSize;
            }


            Control.TextSize = tmpFontSize;

            var layout = new StaticLayout(_currentControlState.JavaText, new TextPaint(Control.Paint), _currentControlState.AvailWidth, Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, true);

            int lines = _currentControlState.Lines;

            if (lines == 0 && _currentControlState.AutoFit == AutoFit.None)
            {
                for (int i = 0; i < layout.LineCount; i++)
                {
                    if (layout.GetLineBottom(i) <= _currentControlState.AvailHeight - layout.TopPadding - layout.BottomPadding)
                    {
                        lines++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (layout.Height > _currentControlState.AvailHeight || (lines > 0 && layout.LineCount > lines))
            {
                if (_currentControlState.Lines == 1)
                {
                    Control.SetSingleLine(true);
                    Control.SetMaxLines(1);
                    Control.Ellipsize = _currentControlState.LineBreakMode.ToEllipsize();
                }
                else
                {
                    layout = F9PTextView.Truncate(_currentControlState.Text, Element.F9PFormattedString, new TextPaint(Control.Paint), _currentControlState.AvailWidth, _currentControlState.AvailHeight, Element.AutoFit, Element.LineBreakMode, ref lines, ref text);
                }
            }
            lines = lines > 0 ? System.Math.Min(lines, layout.LineCount) : layout.LineCount;
            for (int i = 0; i < lines; i++)
            {
                tmpHt = layout.GetLineBottom(i);
                var width = layout.GetLineWidth(i);
                //System.Diagnostics.Debug.WriteLine("\t\tright=["+right+"]");
                if (width > tmpWd)
                {
                    tmpWd = (int)System.Math.Ceiling(width);
                }
            }
            if (_currentControlState.AutoFit == AutoFit.None && _currentControlState.Lines > 0)
            {
                Control.SetMaxLines(_currentControlState.Lines);
            }

            //System.Diagnostics.Debug.WriteLine("\tLabelRenderer.GetDesiredSize\ttmp.size=[" + tmpWd + ", " + tmpHt + "]");
            if (Element.IsDynamicallySized && _currentControlState.Lines > 0 && _currentControlState.AutoFit == AutoFit.Lines)
            {
                fontMetrics    = Control.Paint.GetFontMetrics();
                fontLineHeight = fontMetrics.Descent - fontMetrics.Ascent;
                fontLeading    = System.Math.Abs(fontMetrics.Bottom - fontMetrics.Descent);
                tmpHt          = (int)(fontLineHeight * _currentControlState.Lines + fontLeading * (_currentControlState.Lines - 1));
            }

            Control.Gravity = Element.HorizontalTextAlignment.ToHorizontalGravityFlags() | Element.VerticalTextAlignment.ToVerticalGravityFlags();

            if (Element.Text != null)
            {
                Control.Text = text.ToString();
            }
            else
            {
                Control.TextFormatted = text;
            }

            _lastSizeRequest = new SizeRequest(new Xamarin.Forms.Size(tmpWd, tmpHt), new Xamarin.Forms.Size(10, tmpHt));
            if (showDebugMsg)
            {
                Control.SetWidth((int)_lastSizeRequest.Value.Request.Width);
                Control.SetHeight((int)_lastSizeRequest.Value.Request.Height);

                System.Diagnostics.Debug.WriteLine("\t[" + elementText + "] LabelRenderer.GetDesiredSize(" + (_currentControlState.AvailWidth > int.MaxValue / 3 ? "infinity" : _currentControlState.AvailWidth.ToString()) + "," + (_currentControlState.AvailHeight > int.MaxValue / 3 ? "infinity" : _currentControlState.AvailHeight.ToString()) + ") exit (" + _lastSizeRequest.Value + ")");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Visibility=[" + Control.Visibility + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.TextFormatted=[" + Control.TextFormatted + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.TextSize=[" + Control.TextSize + "]");
                //System.Diagnostics.Debug.WriteLine("\t\tControl.ClipBounds=["+Control.ClipBounds.Width()+","+Control.ClipBounds.Height()+"]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Width[" + Control.Width + "]  .Height=[" + Control.Height + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.GetX[" + Control.GetX() + "]  .GetY[" + Control.GetY() + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Alpha[" + Control.Alpha + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Background[" + Control.Background + "]");
                //System.Diagnostics.Debug.WriteLine("\t\tControl.Elevation["+Control.Elevation+"]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Enabled[" + Control.Enabled + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.Error[" + Control.Error + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.IsOpaque[" + Control.IsOpaque + "]");
                System.Diagnostics.Debug.WriteLine("\t\tControl.IsShown[" + Control.IsShown + "]");
                //Control.BringToFront();
                System.Diagnostics.Debug.WriteLine("\t\t");
            }

            if (Element.LineBreakMode == LineBreakMode.NoWrap)
            {
                Control.SetSingleLine(true);
            }

            _lastControlState = new ControlState(_currentControlState);
            return(_lastSizeRequest.Value);
        }
Exemplo n.º 31
0
        public override Carto.Graphics.Bitmap OnDrawPopup(PopupDrawInfo popupDrawInfo)
        {
            PopupStyle style = popupDrawInfo.Popup.Style;

            // Calculate scaled dimensions
            float DPToPX = popupDrawInfo.DPToPX;
            float PXTODP = 1 / DPToPX;

            if (style.ScaleWithDPI)
            {
                DPToPX = 1;
            }
            else
            {
                PXTODP = 1;
            }

            float screenWidth  = popupDrawInfo.ScreenBounds.GetWidth() * PXTODP;
            float screenHeight = popupDrawInfo.ScreenBounds.GetHeight() * PXTODP;

            // Update sizes based on scale (uses extension method, cf. Shared/Extensions
            int fontSize = FontSize.Update(DPToPX);

            int triangleWidth  = TriangleSize.Update(DPToPX);
            int triangleHeight = TriangleSize.Update(DPToPX);

            int strokeWidth   = StrokeWidth.Update(DPToPX);
            int screenPadding = ScreenPadding.Update(DPToPX);

            // Set font
            var font = Android.Graphics.Typeface.Create("HelveticaNeue-Light", Android.Graphics.TypefaceStyle.Normal);

            // Calculate the maximum popup size, adjust with dpi
            int maxPopupWidth = (int)(Math.Min(screenWidth, screenHeight));

            float halfStrokeWidth = strokeWidth * 0.5f;
            int   maxTextWidth    = maxPopupWidth - (2 * screenPadding + strokeWidth);

            // Measure text
            TextPaint textPaint = new TextPaint {
                Color = TextColor, TextSize = fontSize
            };

            textPaint.SetTypeface(font);

            var textLayout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.AlignNormal, 1, 0, false);

            int textX = (int)Math.Min(textPaint.MeasureText(text), textLayout.Width);
            int textY = textLayout.Height;

            int popupWidth  = textX + (2 * PopupPadding + strokeWidth + triangleWidth);
            int popupHeight = textY + (2 * PopupPadding + strokeWidth);

            var bitmap = Android.Graphics.Bitmap.CreateBitmap(popupWidth, popupHeight, Android.Graphics.Bitmap.Config.Argb8888);
            var canvas = new Android.Graphics.Canvas(bitmap);

            var trianglePath = new Android.Graphics.Path();

            trianglePath.MoveTo(triangleWidth, 0);
            trianglePath.LineTo(halfStrokeWidth, triangleHeight * 0.5f);
            trianglePath.LineTo(triangleWidth, triangleHeight);
            trianglePath.Close();

            int triangleOffsetX = 0;
            int triangleOffsetY = (popupHeight - triangleHeight) / 2;

            // Create paint object
            var paint = new Android.Graphics.Paint();

            paint.AntiAlias = true;
            paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            paint.StrokeWidth = strokeWidth;
            paint.Color       = StrokeColor;

            // Stroke background
            var background = new Android.Graphics.RectF();

            background.Left   = triangleWidth;
            background.Top    = halfStrokeWidth;
            background.Right  = popupWidth - strokeWidth;
            background.Bottom = popupHeight - strokeWidth;
            canvas.DrawRect(background, paint);

            // Stroke triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            // Fill background
            paint.SetStyle(Android.Graphics.Paint.Style.Fill);
            paint.Color = BackgroundColor;
            canvas.DrawRect(background, paint);

            // Fill triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            if (textLayout != null)
            {
                // Draw text
                canvas.Save();
                canvas.Translate(halfStrokeWidth + triangleWidth + PopupPadding, halfStrokeWidth + PopupPadding);
                textLayout.Draw(canvas);
                canvas.Restore();
            }

            return(BitmapUtils.CreateBitmapFromAndroidBitmap(bitmap));
        }
Exemplo n.º 32
0
        //bool _truncating;
        internal static StaticLayout Truncate(string text, F9PFormattedString baseFormattedString, TextPaint paint, int availWidth, int availHeight, AutoFit fit, LineBreakMode lineBreakMode, ref int lines, ref ICharSequence textFormatted)
        {
            StaticLayout layout         = null;
            var          fontMetrics    = paint.GetFontMetrics();
            var          fontLineHeight = fontMetrics.Descent - fontMetrics.Ascent;
            var          fontLeading    = System.Math.Abs(fontMetrics.Bottom - fontMetrics.Descent);

            textFormatted = ((ICharSequence)baseFormattedString?.ToSpannableString()) ?? new Java.Lang.String(text);
            if (lines > 0)
            {
                if (baseFormattedString != null)
                {
                    layout = new StaticLayout(textFormatted, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, true);
                    if (layout.Height > availHeight)
                    {
                        var visibleLines = (int)((fontLeading + availHeight) / (fontLineHeight + fontLeading));
                        if (visibleLines < lines)
                        {
                            lines = visibleLines;
                        }
                    }
                    if (layout.LineCount > lines && lines > 0)
                    {
                        var secondToLastEnd = lines > 1 ? layout.GetLineEnd(lines - 2) : 0;
                        var start           = lines > 1 ? layout.GetLineStart(layout.LineCount - 2) : 0;
                        switch (lineBreakMode)
                        {
                        case LineBreakMode.HeadTruncation:
                            textFormatted = StartTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, start, layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        case LineBreakMode.MiddleTruncation:
                            textFormatted = MidTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), (layout.GetLineEnd(lines - 1) + layout.GetLineStart(lines - 1)) / 2 - 1, start, layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        case LineBreakMode.TailTruncation:
                            textFormatted = EndTruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        default:
                            //textFormatted = baseFormattedString.ToSpannableString(EllipsePlacement.None, 0, 0, layout.GetLineEnd(lines - 1));
                            textFormatted = TruncatedFormatted(baseFormattedString, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;
                        }
                    }
                }
                else
                {
                    layout = new StaticLayout(text, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, true);
                    if (layout.Height > availHeight)
                    {
                        var visibleLines = (int)((fontLeading + availHeight) / (fontLineHeight + fontLeading));
                        if (visibleLines < lines)
                        {
                            lines = visibleLines;
                        }
                    }
                    if (layout.LineCount > lines && lines > 0)
                    {
                        var secondToLastEnd = lines > 1 ? layout.GetLineEnd(lines - 2) : 0;
                        var start           = lines > 1 ? layout.GetLineStart(layout.LineCount - 2) : 0;
                        switch (lineBreakMode)
                        {
                        case LineBreakMode.HeadTruncation:
                            text = StartTruncatedLastLine(text, paint, secondToLastEnd, start, layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        case LineBreakMode.MiddleTruncation:
                            text = MidTruncatedLastLine(text, paint, secondToLastEnd, layout.GetLineStart(lines - 1), (layout.GetLineEnd(lines - 1) + layout.GetLineStart(lines - 1)) / 2 - 1, start, layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        case LineBreakMode.TailTruncation:
                            text = EndTruncatedLastLine(text, paint, secondToLastEnd, layout.GetLineStart(lines - 1), layout.GetLineEnd(layout.LineCount - 1), availWidth);
                            break;

                        default:
                            text = text.Substring(0, layout.GetLineEnd(lines - 1));
                            break;
                        }
                        textFormatted = new Java.Lang.String(text);
                    }
                }
            }
            return(new StaticLayout(textFormatted, paint, availWidth, Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, true));
        }
        private void RenderLabel(Canvas canvas, RadRect dataPointSlot, string labelText, StaticLayout textBounds)
        {
            // TODO - Rotate the canvas on the center before drawing label
            //canvas.Rotate(90, (float)canvas.Width / 2, (float)canvas.Height / 2);

            RectF labelBounds = new RectF();
            float height      = textBounds.Height + labelPadding * 2;

            // Calculate the middle of the bar
            var barY        = (float)dataPointSlot.GetY();
            var barHeight   = canvas.Height - barY;
            var middlePoint = barHeight / 2;
            var labelY      = canvas.Height - middlePoint;

            // Calculate left and right padding around the label
            var barX     = (float)dataPointSlot.GetX();
            var barRight = (float)dataPointSlot.Right;
            var barWidth = barRight - barX;
            var padding  = barWidth / 10;

            // Calculate the Rect bounds
            var rectLeft   = barX + padding;
            var rectTop    = labelY;
            var rectRight  = barRight - padding;
            var rectBottom = rectTop + height;

            // Set's the label's position on the Chart's canvas
            labelBounds.Set(rectLeft, rectTop, rectRight, rectBottom);

            // Draws Rect's fill and stroke color
            canvas.DrawRect(labelBounds.Left, labelBounds.Top, labelBounds.Right, labelBounds.Bottom, fillPaint);
            canvas.DrawRect(labelBounds.Left, labelBounds.Top, labelBounds.Right, labelBounds.Bottom, strokePaint);

            // Draws the Text on the canvas
            canvas.DrawText(
                labelText,
                (float)dataPointSlot.GetX() + (float)(dataPointSlot.Width / 2.0) - textBounds.GetLineWidth(0) / 2.0f,
                labelBounds.CenterY() + textBounds.GetLineBottom(0) - textBounds.GetLineBaseline(0),
                paint);

            // TODO Undo rotation after drawing label
            //canvas.Rotate(-90, (float)canvas.Width / 2, (float)canvas.Height / 2);
        }
Exemplo n.º 34
0
        public void UpdateText(Post post, string tagToExclude, string tagFormat, int maxLines, bool isExpanded)
        {
            var textMaxLength                = int.MaxValue;
            var censorTitle                  = post.Title.CensorText();
            var censorDescription            = post.Description.CensorText();
            var censorDescriptionHtml        = Html.FromHtml(censorDescription);
            var censorDescriptionWithoutHtml = string.IsNullOrEmpty(post.Description)
                ? string.Empty
                : censorDescriptionHtml.ToString();

            if (!isExpanded)
            {
                if (MeasuredWidth == 0)
                {
                    return;
                }

                var titleWithTags = new StringBuilder(censorTitle);
                if (!string.IsNullOrEmpty(censorDescriptionWithoutHtml))
                {
                    titleWithTags.Append(Environment.NewLine + Environment.NewLine);
                    titleWithTags.Append(censorDescriptionWithoutHtml);
                }

                foreach (var item in post.Tags)
                {
                    if (item != tagToExclude)
                    {
                        titleWithTags.AppendFormat(tagFormat, item.TagToRu());
                    }
                }

                var layout = new StaticLayout(titleWithTags.ToString(), Paint, MeasuredWidth, Layout.Alignment.AlignNormal, 1, 1, true);
                var nLines = layout.LineCount;
                if (nLines > maxLines)
                {
                    textMaxLength = layout.GetLineEnd(maxLines - 1) - Localization.Texts.ShowMoreString.Length;
                }
            }

            var builder = new SpannableStringBuilder();
            var buf     = new SpannableString(censorTitle);

            builder.Append(buf);

            if (!string.IsNullOrEmpty(censorDescriptionWithoutHtml))
            {
                var subStrLenght = textMaxLength - censorTitle.Length - Environment.NewLine.Length * 2;
                if (subStrLenght > 0)
                {
                    builder.Append(Environment.NewLine + Environment.NewLine);

                    var outText = censorDescriptionWithoutHtml;
                    if (outText.Length > subStrLenght)
                    {
                        outText = outText.Remove(subStrLenght);
                    }

                    buf = new SpannableString(outText);
                    builder.Append(buf);
                }
            }

            var j    = 0;
            var tags = post.Tags.Distinct();

            foreach (var tag in tags)
            {
                var translitTaf = tag.TagToRu();
                var formatedTag = string.Format(tagFormat, translitTaf);
                if (formatedTag.Length > textMaxLength - builder.Length() - Localization.Texts.ShowMoreString.Length)
                {
                    break;
                }

                if (!string.Equals(tag, tagToExclude, StringComparison.OrdinalIgnoreCase))
                {
                    if (j >= _tags.Count)
                    {
                        var ccs = new CustomClickableSpan();
                        ccs.SpanClicked += TagAction;
                        _tags.Add(ccs);
                    }

                    _tags[j].Tag = translitTaf;
                    buf          = new SpannableString(formatedTag);
                    buf.SetSpan(_tags[j], 0, buf.Length(), SpanTypes.ExclusiveExclusive);
                    buf.SetSpan(new ForegroundColorSpan(Style.R231G72B00), 0, buf.Length(), 0);
                    builder.Append(buf);
                    j++;
                }
            }

            if (textMaxLength != int.MaxValue)
            {
                var tag = new SpannableString(Localization.Texts.ShowMoreString);
                tag.SetSpan(new ForegroundColorSpan(Style.R151G155B158), 0, Localization.Texts.ShowMoreString.Length, 0);
                builder.Append(tag);
            }

            SetText(builder, BufferType.Spannable);
        }
Exemplo n.º 35
0
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);
            //canvas.DrawBitmap(bitmap, 0, 0, p);
            foreach (var p in points)
            {
                if (p.view != null)
                {
                    Rect r = new Rect();
                    p.view.GetGlobalVisibleRect(r);
                    //points.Add(new pointr() { p = new Point(r.Left, r.Top), radius = r.Width() });

                    switch (p.shape)
                    {
                    case HelpOverlay.OverlayShape.ROUND:

                        tmp.DrawCircle(r.Left + r.Width() / 2, r.Top + r.Width() / 2, r.Width(), transparentPaint);
                        tmp.DrawCircle(r.Left + r.Width() / 2, r.Top + r.Width() / 2, r.Width(), blueline);
                        break;

                    case HelpOverlay.OverlayShape.SQUARE:
                        tmp.DrawRect(r.Left - Utils.dp2px(Context, 5), r.Top - Utils.dp2px(Context, 5), r.Right + Utils.dp2px(Context, 10), r.Bottom + Utils.dp2px(Context, 10), transparentPaint);
                        tmp.DrawRect(r.Left - Utils.dp2px(Context, 5), r.Top - Utils.dp2px(Context, 5), r.Right + Utils.dp2px(Context, 10), r.Bottom + Utils.dp2px(Context, 10), blueline);
                        break;
                    }

                    if (r.Left > canvas.Width / 2)
                    {
                        textPaint.TextAlign = Paint.Align.Right;
                        tmp.DrawText(p.view.ContentDescription?.ToString() ?? p.view.Id.ToString(), r.Left - r.Width(), r.Top + r.Width() / 2, textPaint);
                    }
                    else
                    {
                        textPaint.TextAlign = Paint.Align.Right;
                        tmp.DrawText(p.view.ContentDescription?.ToString() ?? p.view.Id.ToString(), r.Right + r.Width(), r.Top + r.Width() / 2, textPaint);
                    }
                }
                else
                {
                    Rect r = p.rec;
                    switch (p.shape)
                    {
                    case HelpOverlay.OverlayShape.ROUND:
                        tmp.DrawCircle(r.Left + r.Width() / 2, r.Top + r.Width() / 2, r.Width(), transparentPaint);
                        tmp.DrawCircle(r.Left + r.Width() / 2, r.Top + r.Width() / 2, r.Width(), blueline);
                        break;

                    case HelpOverlay.OverlayShape.SQUARE:
                        tmp.DrawRect(r.Left - Utils.dp2px(Context, 5), r.Top - Utils.dp2px(Context, 5), r.Right + Utils.dp2px(Context, 10), r.Bottom + Utils.dp2px(Context, 10), transparentPaint);
                        tmp.DrawRect(r.Left - Utils.dp2px(Context, 5), r.Top - Utils.dp2px(Context, 5), r.Right + Utils.dp2px(Context, 10), r.Bottom + Utils.dp2px(Context, 10), blueline);
                        break;
                    }

                    switch (p.position)
                    {
                    case GravityFlags.Top:
                        textPaint.TextAlign = Paint.Align.Left;
                        tmp.DrawText(p.text, r.Left, r.Top - Utils.dp2px(Context, 20), textPaint);
                        break;

                    case GravityFlags.Bottom:
                        textPaint.TextAlign = Paint.Align.Left;
                        tmp.DrawText(p.text, r.Left - Utils.dp2px(Context, 20), r.Bottom + Utils.dp2px(Context, 40), textPaint);
                        break;

                    case GravityFlags.Left:
                        textPaint.TextAlign = Paint.Align.Left;
                        tmp.DrawText(p.text, r.Left - r.Width(), r.Top + r.Width() / 2, textPaint);
                        break;

                    case GravityFlags.Right:
                        TextPaint    mTextPaint  = new TextPaint(textPaint);
                        StaticLayout mTextLayout = new StaticLayout(p.text, mTextPaint, canvas.Width - (r.Left + r.Width() + Utils.dp2px(Context, 15)), Android.Text.Layout.Alignment.AlignNormal, 1.0f, 0.0f, false);
                        // calculate x and y position where your text will be placed
                        tmp.Save();
                        tmp.Translate(r.Right + Utils.dp2px(Context, 15), r.Top + Utils.dp2px(Context, 15));
                        mTextLayout.Draw(tmp);
                        tmp.Restore();
                        //textPaint.TextAlign = Paint.Align.Left;
                        //tmp.DrawText(p.text, r.Right + Utils.dp2px(Context, 15), r.Top + r.Width() / 2, textPaint);
                        break;
                    }
                }
            }
            canvas.DrawBitmap(bmp, 0, 0, null);
        }
Exemplo n.º 36
0
        protected override void OnDraw(Canvas canvas)
        {
            var scale = this.Context.Resources.DisplayMetrics.Density;

            var frame = GetFramingRect();

            if (frame == null)
            {
                return;
            }

            var width  = canvas.Width;
            var height = canvas.Height;

            paint.Color = resultBitmap != null ? resultColor : maskColor;
            paint.Alpha = 100;

            canvas.DrawRect(0, 0, width, frame.Top, paint);
            //canvas.DrawRect(0, frame.Top, frame.Left, frame.Bottom + 1, paint);
            //canvas.DrawRect(frame.Right + 1, frame.Top, width, frame.Bottom + 1, paint);
            canvas.DrawRect(0, frame.Bottom + 1, width, height, paint);

            var textPaint = new TextPaint();

            textPaint.Color    = Color.White;
            textPaint.TextSize = 16 * scale;

            if (!string.IsNullOrEmpty(this.TopText))
            {
                var topTextLayout = new StaticLayout(this.TopText, textPaint, canvas.Width, Android.Text.Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
                canvas.Save();
                Rect topBounds = new Rect();

                textPaint.GetTextBounds(this.TopText, 0, this.TopText.Length, topBounds);
                canvas.Translate(0, frame.Top / 2 - (topTextLayout.Height / 2));

                //canvas.Translate(topBounds.Left, topBounds.Bottom);
                topTextLayout.Draw(canvas);

                canvas.Restore();
            }


            if (!string.IsNullOrEmpty(this.BottomText))
            {
                var botTextLayout = new StaticLayout(this.BottomText, textPaint, canvas.Width, Android.Text.Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
                canvas.Save();
                Rect botBounds = new Rect();

                textPaint.GetTextBounds(this.BottomText, 0, this.BottomText.Length, botBounds);
                canvas.Translate(0, (frame.Bottom + (canvas.Height - frame.Bottom) / 2) - (botTextLayout.Height / 2));

                //canvas.Translate(topBounds.Left, topBounds.Bottom);
                botTextLayout.Draw(canvas);

                canvas.Restore();
            }



            if (resultBitmap != null)
            {
                paint.Alpha = CURRENT_POINT_OPACITY;
                canvas.DrawBitmap(resultBitmap, null, new RectF(frame.Left, frame.Top, frame.Right, frame.Bottom), paint);
            }
            else
            {
                // Draw a two pixel solid black border inside the framing rect
                paint.Color = frameColor;
                //canvas.DrawRect(frame.Left, frame.Top, frame.Right + 1, frame.Top + 2, paint);
                //canvas.DrawRect(frame.Left, frame.Top + 2, frame.Left + 2, frame.Bottom - 1, paint);
                //canvas.DrawRect(frame.Right - 1, frame.Top, frame.Right + 1, frame.Bottom - 1, paint);
                //canvas.DrawRect(frame.Left, frame.Bottom - 1, frame.Right + 1, frame.Bottom + 1, paint);

                // Draw a red "laser scanner" line through the middle to show decoding is active
                paint.Color  = laserColor;
                paint.Alpha  = SCANNER_ALPHA[scannerAlpha];
                scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.Length;
                int middle = frame.Height() / 2 + frame.Top;
                //int middle = frame.Width() / 2 + frame.Left;

                //canvas.DrawRect(frame.Left + 2, middle - 1, frame.Right - 1, middle + 2, paint);

                canvas.DrawRect(0, middle - 1, width, middle + 2, paint);
                //canvas.DrawRect(middle - 1, frame.Top + 2, middle + 2, frame.Bottom - 1, paint); //frame.Top + 2, middle - 1, frame.Bottom - 1, middle + 2, paint);

                //var previewFrame = scanner.GetFramingRectInPreview();
                //float scaleX = frame.Width() / (float) previewFrame.Width();
                //float scaleY = frame.Height() / (float) previewFrame.Height();

                /*var currentPossible = possibleResultPoints;
                 * var currentLast = lastPossibleResultPoints;
                 *
                 * int frameLeft = frame.Left;
                 * int frameTop = frame.Top;
                 *
                 * if (currentPossible == null || currentPossible.Count <= 0)
                 * {
                 * lastPossibleResultPoints = null;
                 * }
                 * else
                 * {
                 *      possibleResultPoints = new List<com.google.zxing.ResultPoint>(5);
                 *      lastPossibleResultPoints = currentPossible;
                 *      paint.Alpha = CURRENT_POINT_OPACITY;
                 *      paint.Color = resultPointColor;
                 *
                 *      lock (currentPossible)
                 *      {
                 *              foreach (var point in currentPossible)
                 *              {
                 *                      canvas.DrawCircle(frameLeft + (int) (point.X * scaleX),
                 * frameTop + (int) (point.Y * scaleY), POINT_SIZE, paint);
                 *              }
                 *      }
                 * }
                 *
                 * if (currentLast != null)
                 * {
                 *      paint.Alpha = CURRENT_POINT_OPACITY / 2;
                 *      paint.Color = resultPointColor;
                 *
                 *      lock (currentLast)
                 *      {
                 *              float radius = POINT_SIZE / 2.0f;
                 *              foreach (var point in currentLast)
                 *              {
                 *                      canvas.DrawCircle(frameLeft + (int) (point.X * scaleX),
                 * frameTop + (int) (point.Y * scaleY), radius, paint);
                 *              }
                 *      }
                 * }
                 */

                // Request another update at the animation interval, but only repaint the laser line,
                // not the entire viewfinder mask.
                PostInvalidateDelayed(ANIMATION_DELAY,
                                      frame.Left - POINT_SIZE,
                                      frame.Top - POINT_SIZE,
                                      frame.Right + POINT_SIZE,
                                      frame.Bottom + POINT_SIZE);
            }

            base.OnDraw(canvas);
        }
        public static void drawClock(SKCanvas canvas, Context context, SKRect targetFrame, ResizingBehavior resizing, SKColor numbersColor, SKColor darkHandsColor, SKColor lightHandColor, SKColor rimColor, SKColor tickColor, SKColor faceColor, float hours, float minutes, float seconds)
        {
            // General Declarations
//         Stack<Matrix> currentTransformation = new Stack<Matrix>(); // skipping - we do not support Matrix yet
//         currentTransformation.push(new Matrix()); // skipping - we do not support Matrix yet
            SKPaint paint = CacheForClock.paint;

            // Local Variables
            String expression   = hours > 12f ? "PM" : "AM";
            float  secondsAngle = -seconds / 60f * 360f;
            float  minuteAngle  = -(minutes / 60f * 360f - secondsAngle / 60f);
            float  hourAngle    = -hours / 12f * 360f + minuteAngle / 12f;

            // Resize to Target Frame
            canvas.Save();
            var resizedFrame = Helpers.ResizingBehaviorApply(resizing, CacheForClock.originalFrame, targetFrame);

            canvas.Translate(resizedFrame.Left, resizedFrame.Top);
            canvas.Scale(resizedFrame.Width / 260f, resizedFrame.Height / 260f);

            // Oval 2
            canvas.Save();
            canvas.Translate(130f, 130f);
//         currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
            var    oval2Rect = new SKRect(-116f, -116f, 116f, 116f);
            SKPath oval2Path = CacheForClock.oval2Path;

            oval2Path.Reset();
            oval2Path.AddOval(oval2Rect, SKPathDirection.Clockwise);

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)rimColor;
            canvas.DrawPath(oval2Path, paint);
            canvas.Restore();

            // Oval
            canvas.Save();
            canvas.Translate(130f, 130f);
//         currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
            var    ovalRect = new SKRect(-110f, -110f, 110f, 110f);
            SKPath ovalPath = CacheForClock.ovalPath;

            ovalPath.Reset();
            ovalPath.AddOval(ovalRect, SKPathDirection.Clockwise);

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)faceColor;
            canvas.DrawPath(ovalPath, paint);
            canvas.Restore();

            // Text
            var    textRect = new SKRect(118.48f, 34.85f, 142.5f, 53f);
            SKPath textPath = CacheForClock.textPath;

            textPath.Reset();
            textPath.MoveTo(123.73f, 38.95f);
            textPath.LineTo(120.23f, 41.82f);
            textPath.LineTo(118.48f, 39.75f);
            textPath.LineTo(124f, 35.3f);
            textPath.LineTo(126.73f, 35.3f);
            textPath.LineTo(126.73f, 53f);
            textPath.LineTo(123.73f, 53f);
            textPath.LineTo(123.73f, 38.95f);
            textPath.Close();
            textPath.MoveTo(130.73f, 50.25f);
            textPath.LineTo(137.55f, 43.55f);
            textPath.CubicTo(138.1f, 43.02f, 138.54f, 42.48f, 138.86f, 41.94f);
            textPath.CubicTo(139.19f, 41.4f, 139.35f, 40.78f, 139.35f, 40.07f);
            textPath.CubicTo(139.35f, 39.24f, 139.08f, 38.58f, 138.54f, 38.09f);
            textPath.CubicTo(138f, 37.6f, 137.33f, 37.35f, 136.53f, 37.35f);
            textPath.CubicTo(135.67f, 37.35f, 134.99f, 37.64f, 134.48f, 38.21f);
            textPath.CubicTo(133.96f, 38.79f, 133.64f, 39.51f, 133.53f, 40.38f);
            textPath.LineTo(130.6f, 39.92f);
            textPath.CubicTo(130.68f, 39.19f, 130.89f, 38.52f, 131.23f, 37.9f);
            textPath.CubicTo(131.56f, 37.28f, 131.98f, 36.75f, 132.5f, 36.3f);
            textPath.CubicTo(133.02f, 35.85f, 133.62f, 35.5f, 134.31f, 35.24f);
            textPath.CubicTo(135f, 34.98f, 135.76f, 34.85f, 136.57f, 34.85f);
            textPath.CubicTo(137.34f, 34.85f, 138.08f, 34.96f, 138.79f, 35.17f);
            textPath.CubicTo(139.5f, 35.39f, 140.12f, 35.72f, 140.68f, 36.16f);
            textPath.CubicTo(141.23f, 36.6f, 141.66f, 37.15f, 141.99f, 37.79f);
            textPath.CubicTo(142.31f, 38.43f, 142.48f, 39.17f, 142.48f, 40.03f);
            textPath.CubicTo(142.48f, 40.59f, 142.4f, 41.12f, 142.25f, 41.61f);
            textPath.CubicTo(142.1f, 42.1f, 141.9f, 42.57f, 141.64f, 43f);
            textPath.CubicTo(141.38f, 43.43f, 141.08f, 43.85f, 140.74f, 44.24f);
            textPath.CubicTo(140.4f, 44.63f, 140.03f, 45.01f, 139.63f, 45.38f);
            textPath.LineTo(134.53f, 50.25f);
            textPath.LineTo(142.5f, 50.25f);
            textPath.LineTo(142.5f, 53f);
            textPath.LineTo(130.73f, 53f);
            textPath.LineTo(130.73f, 50.25f);
            textPath.Close();

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)numbersColor;
            canvas.DrawPath(textPath, paint);

            // Bezier
            canvas.Save();
            canvas.Translate(130f, 130f);
//         currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
            canvas.RotateDegrees(-(minuteAngle + 90f));
//         currentTransformation.peek().postRotate(-(minuteAngle + 90f)); // skipping - we do not support Matrix yet
            var    bezierRect = new SKRect(-10f, -10f, 95f, 10f);
            SKPath bezierPath = CacheForClock.bezierPath;

            bezierPath.Reset();
            bezierPath.MoveTo(7.07f, -7.07f);
            bezierPath.CubicTo(8.25f, -5.89f, 9.07f, -4.49f, 9.54f, -3f);
            bezierPath.LineTo(95f, -3f);
            bezierPath.LineTo(95f, 3f);
            bezierPath.LineTo(9.54f, 3f);
            bezierPath.CubicTo(9.07f, 4.49f, 8.25f, 5.89f, 7.07f, 7.07f);
            bezierPath.CubicTo(3.17f, 10.98f, -3.17f, 10.98f, -7.07f, 7.07f);
            bezierPath.CubicTo(-10.98f, 3.17f, -10.98f, -3.17f, -7.07f, -7.07f);
            bezierPath.CubicTo(-3.17f, -10.98f, 3.17f, -10.98f, 7.07f, -7.07f);
            bezierPath.Close();

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)darkHandsColor;
            canvas.DrawPath(bezierPath, paint);
            canvas.Restore();

            // Bezier 2
            canvas.Save();
            canvas.Translate(130f, 130f);
//         currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
            canvas.RotateDegrees(-(hourAngle + 90f));
//         currentTransformation.peek().postRotate(-(hourAngle + 90f)); // skipping - we do not support Matrix yet
            var    bezier2Rect = new SKRect(-10f, -10f, 56f, 10f);
            SKPath bezier2Path = CacheForClock.bezier2Path;

            bezier2Path.Reset();
            bezier2Path.MoveTo(7.07f, -7.07f);
            bezier2Path.CubicTo(7.7f, -6.44f, 8.24f, -5.74f, 8.66f, -5f);
            bezier2Path.LineTo(56f, -5f);
            bezier2Path.LineTo(56f, 5f);
            bezier2Path.LineTo(8.66f, 5f);
            bezier2Path.CubicTo(8.24f, 5.74f, 7.7f, 6.44f, 7.07f, 7.07f);
            bezier2Path.CubicTo(3.17f, 10.98f, -3.17f, 10.98f, -7.07f, 7.07f);
            bezier2Path.CubicTo(-10.98f, 3.17f, -10.98f, -3.17f, -7.07f, -7.07f);
            bezier2Path.CubicTo(-3.17f, -10.98f, 3.17f, -10.98f, 7.07f, -7.07f);
            bezier2Path.Close();

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)darkHandsColor;
            canvas.DrawPath(bezier2Path, paint);
            canvas.Restore();

            // Bezier 3
            canvas.Save();
            canvas.Translate(130f, 130f);
//         currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
            canvas.RotateDegrees(-(secondsAngle + 90f));
//         currentTransformation.peek().postRotate(-(secondsAngle + 90f)); // skipping - we do not support Matrix yet
            var    bezier3Rect = new SKRect(-6f, -6f, 99f, 6f);
            SKPath bezier3Path = CacheForClock.bezier3Path;

            bezier3Path.Reset();
            bezier3Path.MoveTo(4.24f, -4.24f);
            bezier3Path.CubicTo(5.16f, -3.33f, 5.72f, -2.19f, 5.92f, -1f);
            bezier3Path.LineTo(99f, -1f);
            bezier3Path.LineTo(99f, 1f);
            bezier3Path.LineTo(5.92f, 1f);
            bezier3Path.CubicTo(5.72f, 2.19f, 5.16f, 3.33f, 4.24f, 4.24f);
            bezier3Path.CubicTo(1.9f, 6.59f, -1.9f, 6.59f, -4.24f, 4.24f);
            bezier3Path.CubicTo(-6.59f, 1.9f, -6.59f, -1.9f, -4.24f, -4.24f);
            bezier3Path.CubicTo(-1.9f, -6.59f, 1.9f, -6.59f, 4.24f, -4.24f);
            bezier3Path.Close();

            paint.Reset();
            paint.IsAntialias = true;
            paint.Style       = SKPaintStyle.Fill;
            paint.Color       = (SKColor)lightHandColor;
            canvas.DrawPath(bezier3Path, paint);
            canvas.Restore();

            // Group
            {
                // Rectangle
                var    rectangleRect = new SKRect(127f, 20f, 133f, 28f);
                SKPath rectanglePath = CacheForClock.rectanglePath;
                rectanglePath.Reset();
                rectanglePath.AddRect(rectangleRect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectanglePath, paint);

                // Rectangle 2
                var    rectangle2Rect = new SKRect(127f, 232f, 133f, 240f);
                SKPath rectangle2Path = CacheForClock.rectangle2Path;
                rectangle2Path.Reset();
                rectangle2Path.AddRect(rectangle2Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle2Path, paint);
            }

            // Group 2
            {
                canvas.Save();
                canvas.Translate(130f, 130f);
//             currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
                canvas.RotateDegrees(90f);
//             currentTransformation.peek().postRotate(90f); // skipping - we do not support Matrix yet

                // Rectangle 3
                var    rectangle3Rect = new SKRect(-3f, -110f, 3f, -102f);
                SKPath rectangle3Path = CacheForClock.rectangle3Path;
                rectangle3Path.Reset();
                rectangle3Path.AddRect(rectangle3Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle3Path, paint);

                // Rectangle 4
                var    rectangle4Rect = new SKRect(-3f, 102f, 3f, 110f);
                SKPath rectangle4Path = CacheForClock.rectangle4Path;
                rectangle4Path.Reset();
                rectangle4Path.AddRect(rectangle4Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle4Path, paint);

                canvas.Restore();
            }

            // Group 3
            {
                canvas.Save();
                canvas.Translate(130f, 130f);
//             currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
                canvas.RotateDegrees(-30f);
//             currentTransformation.peek().postRotate(-30f); // skipping - we do not support Matrix yet

                // Rectangle 5
                var    rectangle5Rect = new SKRect(-3f, -110f, 3f, -102f);
                SKPath rectangle5Path = CacheForClock.rectangle5Path;
                rectangle5Path.Reset();
                rectangle5Path.AddRect(rectangle5Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle5Path, paint);

                // Rectangle 6
                var    rectangle6Rect = new SKRect(-3f, 102f, 3f, 110f);
                SKPath rectangle6Path = CacheForClock.rectangle6Path;
                rectangle6Path.Reset();
                rectangle6Path.AddRect(rectangle6Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle6Path, paint);

                canvas.Restore();
            }

            // Group 4
            {
                canvas.Save();
                canvas.Translate(130f, 130f);
//             currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
                canvas.RotateDegrees(-60f);
//             currentTransformation.peek().postRotate(-60f); // skipping - we do not support Matrix yet

                // Rectangle 7
                var    rectangle7Rect = new SKRect(-3f, -110f, 3f, -102f);
                SKPath rectangle7Path = CacheForClock.rectangle7Path;
                rectangle7Path.Reset();
                rectangle7Path.AddRect(rectangle7Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle7Path, paint);

                // Rectangle 8
                var    rectangle8Rect = new SKRect(-3f, 102f, 3f, 110f);
                SKPath rectangle8Path = CacheForClock.rectangle8Path;
                rectangle8Path.Reset();
                rectangle8Path.AddRect(rectangle8Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle8Path, paint);

                canvas.Restore();
            }

            // Group 5
            {
                canvas.Save();
                canvas.Translate(130f, 130f);
//             currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
                canvas.RotateDegrees(-120f);
//             currentTransformation.peek().postRotate(-120f); // skipping - we do not support Matrix yet

                // Rectangle 9
                var    rectangle9Rect = new SKRect(-3f, -110f, 3f, -102f);
                SKPath rectangle9Path = CacheForClock.rectangle9Path;
                rectangle9Path.Reset();
                rectangle9Path.AddRect(rectangle9Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle9Path, paint);

                // Rectangle 10
                var    rectangle10Rect = new SKRect(-3f, 102f, 3f, 110f);
                SKPath rectangle10Path = CacheForClock.rectangle10Path;
                rectangle10Path.Reset();
                rectangle10Path.AddRect(rectangle10Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle10Path, paint);

                canvas.Restore();
            }

            // Group 6
            {
                canvas.Save();
                canvas.Translate(130f, 130f);
//             currentTransformation.peek().postTranslate(130f, 130f); // skipping - we do not support Matrix yet
                canvas.RotateDegrees(-150f);
//             currentTransformation.peek().postRotate(-150f); // skipping - we do not support Matrix yet

                // Rectangle 11
                var    rectangle11Rect = new SKRect(-3f, -110f, 3f, -102f);
                SKPath rectangle11Path = CacheForClock.rectangle11Path;
                rectangle11Path.Reset();
                rectangle11Path.AddRect(rectangle11Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle11Path, paint);

                // Rectangle 12
                var    rectangle12Rect = new SKRect(-3f, 102f, 3f, 110f);
                SKPath rectangle12Path = CacheForClock.rectangle12Path;
                rectangle12Path.Reset();
                rectangle12Path.AddRect(rectangle12Rect, SKPathDirection.Clockwise);

                paint.Reset();
                paint.IsAntialias = true;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = (SKColor)tickColor;
                canvas.DrawPath(rectangle12Path, paint);

                canvas.Restore();
            }

            // Text 2
            var text2Rect      = new SKRect(111f, 198f, 149f, 238f);
            var text2TextPaint = CacheForClock.text2TextPaint;

            text2TextPaint.Reset();
            text2TextPaint.IsAntialias = true;
            text2TextPaint.Color       = (SKColor)numbersColor;
            text2TextPaint.Typeface    = TypefaceManager.GetTypeface("Avenir Next.ttc");
            text2TextPaint.TextSize    = 25f;
            StaticLayout text2StaticLayout = CacheForClock.text2StaticLayout.get((int)text2Rect.Width, SKTextAlign.Center, "6", text2TextPaint);

            canvas.Save();
            canvas.ClipRect(text2Rect);
            canvas.Translate(text2Rect.Left, text2Rect.Top + (text2Rect.Height - text2StaticLayout.getHeight()) / 2f);
            text2StaticLayout.draw(canvas);
            canvas.Restore();

            // Text 3
            var text3Rect      = new SKRect(201f, 110f, 239f, 150f);
            var text3TextPaint = CacheForClock.text3TextPaint;

            text3TextPaint.Reset();
            text3TextPaint.IsAntialias = true;
            text3TextPaint.Color       = (SKColor)numbersColor;
            text3TextPaint.Typeface    = TypefaceManager.GetTypeface("Avenir Next.ttc");
            text3TextPaint.TextSize    = 25f;
            StaticLayout text3StaticLayout = CacheForClock.text3StaticLayout.get((int)text3Rect.Width, SKTextAlign.Center, "3", text3TextPaint);

            canvas.Save();
            canvas.ClipRect(text3Rect);
            canvas.Translate(text3Rect.Left, text3Rect.Top + (text3Rect.Height - text3StaticLayout.getHeight()) / 2f);
            text3StaticLayout.draw(canvas);
            canvas.Restore();

            // Text 4
            var text4Rect      = new SKRect(22f, 110f, 60f, 150f);
            var text4TextPaint = CacheForClock.text4TextPaint;

            text4TextPaint.Reset();
            text4TextPaint.IsAntialias = true;
            text4TextPaint.Color       = (SKColor)numbersColor;
            text4TextPaint.Typeface    = TypefaceManager.GetTypeface("Avenir Next.ttc");
            text4TextPaint.TextSize    = 25f;
            StaticLayout text4StaticLayout = CacheForClock.text4StaticLayout.get((int)text4Rect.Width, SKTextAlign.Center, "9", text4TextPaint);

            canvas.Save();
            canvas.ClipRect(text4Rect);
            canvas.Translate(text4Rect.Left, text4Rect.Top + (text4Rect.Height - text4StaticLayout.getHeight()) / 2f);
            text4StaticLayout.draw(canvas);
            canvas.Restore();

            // Text 13
            var text13Rect      = new SKRect(99f, 144f, 161f, 178f);
            var text13TextPaint = CacheForClock.text13TextPaint;

            text13TextPaint.Reset();
            text13TextPaint.IsAntialias = true;
            text13TextPaint.Color       = (SKColor)numbersColor;
            text13TextPaint.Typeface    = TypefaceManager.GetTypeface("Avenir Next.ttc");
            text13TextPaint.TextSize    = 20f;
            StaticLayout text13StaticLayout = CacheForClock.text13StaticLayout.get((int)text13Rect.Width, SKTextAlign.Center, expression, text13TextPaint);

            canvas.Save();
            canvas.ClipRect(text13Rect);
            canvas.Translate(text13Rect.Left, text13Rect.Top + (text13Rect.Height - text13StaticLayout.getHeight()) / 2f);
            text13StaticLayout.draw(canvas);
            canvas.Restore();

            canvas.Restore();
        }
Exemplo n.º 38
0
        // Resize the text size with specified width and height
        public void ResizeText(int width, int height)
        {
            ICharSequence text = new Java.Lang.String(Text);

            // Do not resize if the view does not have dimensions or there is no text
            if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || mTextSize == 0)
            {
                return;
            }
            if (TransformationMethod != null)
            {
                text = TransformationMethod.GetTransformationFormatted(text, this);
            }
            // Get the text view's paint object
            TextPaint textPaint = Paint;
            // Store the current text size
            float oldTextSize = textPaint.TextSize;
            // If there is a max text size set, use the lesser of that and the default text size
            float targetTextSize = mMaxTextSize > 0 ? Math.Min(mTextSize, mMaxTextSize) : mTextSize;

            // Get the required text height
            int textHeight = GetTextHeight(text, textPaint, width, targetTextSize);

            // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
            while (textHeight > height && targetTextSize > mMinTextSize)
            {
                targetTextSize = Math.Max(targetTextSize - 2, mMinTextSize);
                textHeight     = GetTextHeight(text, textPaint, width, targetTextSize);
            }

            // If we had reached our minimum text size and still don't fit, append an ellipsis
            if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height)
            {
                TextPaint paint = new TextPaint(textPaint);
                // Draw using a static layout
                StaticLayout layout = new StaticLayout(text, paint, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
                // Check that we have a least one line of rendered text
                if (layout.LineCount > 0)
                {
                    // Since the line at the specific vertical position would be cut off,
                    // we must trim up to the previous line
                    int lastLine = layout.GetLineForVertical(height) - 1;
                    // If the text would not even fit on a single line, clear it
                    if (lastLine < 0)
                    {
                        Text = "";
                    }
                    // Otherwise, trim to the previous line and add an ellipsis
                    else
                    {
                        int   start        = layout.GetLineStart(lastLine);
                        int   end          = layout.GetLineEnd(lastLine);
                        float lineWidth    = layout.GetLineWidth(lastLine);
                        float ellipseWidth = textPaint.MeasureText(mEllipsis);

                        // Trim characters off until we have enough room to draw the ellipsis
                        while (width < lineWidth + ellipseWidth)
                        {
                            lineWidth = textPaint.MeasureText(text.SubSequence(start, --end + 1).ToString());
                        }
                        Text = (text.SubSequence(0, end) + mEllipsis);
                    }
                }
            }

            // Some devices try to auto adjust line spacing, so force default line spacing
            // and invalidate the layout as a side effect
            SetTextSize(ComplexUnitType.Px, targetTextSize);
            SetLineSpacing(mSpacingAdd, mSpacingMult);

            // Notify the listener if registered
            if (mTextResizeListener != null)
            {
                mTextResizeListener.OnTextResize(this, oldTextSize, targetTextSize);
            }

            // Reset force resize flag
            mNeedsResize = false;
        }
Exemplo n.º 39
0
 public static Drawing.SizeF GetTextSize(this StaticLayout target)
 {
     // Get the text bounds and assume (the safe assumption) that the layout wasn't
     // created with a bounded width.
     return(GetTextSize(target, false));
 }