Exemplo n.º 1
1
		void CreateBitmapData (string str, out byte[] bitmapData, out int width, out int height)
		{
			Paint paint = new Paint ();
			paint.TextSize = 128;
			paint.TextAlign = Paint.Align.Left;
			paint.SetTypeface (Typeface.Default);
			width = height = 256;
			float textWidth = paint.MeasureText (str);

			using (Bitmap bitmap = Bitmap.CreateBitmap (width, height, Bitmap.Config.Argb8888)) {
				Canvas canvas = new Canvas (bitmap);
				paint.Color = str != " " ? Color.White : Color.LightGray;
				canvas.DrawRect (new Rect (0, 0, width, height), paint);
				paint.Color = Color.Black;
				canvas.DrawText (str, (256 - textWidth) / 2f, (256 - paint.Descent () - paint.Ascent ()) / 2f, paint);
				bitmapData = new byte [width * height * 4];
				Java.Nio.ByteBuffer buffer = Java.Nio.ByteBuffer.Allocate (bitmapData.Length);
				bitmap.CopyPixelsToBuffer (buffer);
				buffer.Rewind ();
				buffer.Get (bitmapData, 0, bitmapData.Length);
			}
		}
Exemplo n.º 2
0
        public Task <Bitmap> LoadImageAsync(
            ImageSource imagesource,
            Context context,
            CancellationToken cancelationToken = default(CancellationToken))
        {
            Bitmap image      = null;
            var    fontsource = imagesource as FontImageSource;

            if (fontsource != null)
            {
                using var paint = new Paint
                      {
                          TextSize  = TypedValue.ApplyDimension(ComplexUnitType.Dip, (float)fontsource.Size, context.Resources.DisplayMetrics),
                          Color     = (fontsource.Color != null ? fontsource.Color : Colors.White).ToAndroid(),
                          TextAlign = Paint.Align.Left,
                          AntiAlias = true,
                      };

                paint.SetTypeface(fontsource.FontFamily.ToTypeface());

                var width    = (int)(paint.MeasureText(fontsource.Glyph) + .5f);
                var baseline = (int)(-paint.Ascent() + .5f);
                var height   = (int)(baseline + paint.Descent() + .5f);
                image            = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                using var canvas = new Canvas(image);
                canvas.DrawText(fontsource.Glyph, 0, baseline, paint);
            }

            return(Task.FromResult(image));
        }
Exemplo n.º 3
0
        public static float AdjustTextToSize(string text, SizeF box, float edgeInset, Context context)
        {
            SizeF constrainSize = new SizeF (box.Width - edgeInset, 9999);
            float toReturn = 0f;

            Paint paint = new Paint (PaintFlags.AntiAlias);
            paint.TextSize = 16f;
            paint.SetTypeface (Typeface.Default);
            float height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);

            if (height > box.Height - edgeInset) {

                do {
                    height -= 0.5f;
                    paint.TextSize = height;
                    height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);
                } while (height > box.Height - edgeInset);

                toReturn = paint.TextSize;

            } else if (height < box.Height - edgeInset) {

                do {
                    height += 0.5f;
                    paint.TextSize = height;
                    height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);

                } while (height < box.Height - edgeInset);

                toReturn = paint.TextSize;

            } else {

                toReturn = paint.TextSize;

            }//end if else

            return toReturn;
        }
        protected override void OnDraw(Android.Graphics.Canvas canvas)
        {
            String rdText = this.Text.ToString();
            Paint textPaint = new Paint();
            textPaint.AntiAlias = true;
            textPaint.TextSize = this.TextSize;
            textPaint.TextAlign = Android.Graphics.Paint.Align.Center;

            float canvasWidth = canvas.Width;
            float textWidth = textPaint.MeasureText(rdText);

            if (Checked)
            {
                this.SetBackgroundResource(Resource.Drawable.RoundedShape);
                int[] colors = new int[] { this.Context.Resources.GetColor(Resource.Color.radioUnselectTop), this.Context.Resources.GetColor(Resource.Color.radioSelectTop )};
                GradientDrawable grad = new GradientDrawable(GradientDrawable.Orientation.TopBottom, colors);
                grad.SetBounds(0, 0, this.Width, this.Height);
                grad.SetCornerRadius(7f);
                this.SetBackgroundDrawable(grad);
            }
            else
            {
                this.SetBackgroundResource(Resource.Drawable.RoundedShape);
                int[] colors = new int[] { this.Context.Resources.GetColor(Resource.Color.radioUnselectTop), this.Context.Resources.GetColor(Resource.Color.radioUnselectBottom) };
                GradientDrawable grad = new GradientDrawable(GradientDrawable.Orientation.TopBottom, colors);
                grad.SetBounds(0, 0, this.Width, this.Height);
                grad.SetCornerRadius(7f);
                this.SetBackgroundDrawable(grad);
            }

            Paint paint = new Paint();
            paint.Color = Color.Transparent;
            paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            Rect rect = new Rect(0, 0, this.Width, this.Height);
            canvas.DrawRect(rect, paint);

            base.OnDraw(canvas);
        }
 private Rect CalcBounds(int index, Paint paint)
 {
     var bounds = new Rect();
     var title = GetTitle(index);
     bounds.Right = (int)paint.MeasureText(title);
     bounds.Bottom = (int)(paint.Descent() - paint.Ascent());
     return bounds;
 }
 /**
  * Calculate the bounds for a view's title
  *
  * @param index
  * @param paint
  * @return
  */
 private RectF CalcBounds(int index, Paint paint)
 {
     //Calculate the text bounds
     RectF bounds = new RectF();
     bounds.Right = paint.MeasureText(mTitleProvider.GetTitle(index));
     bounds.Bottom = paint.Descent() - paint.Ascent();
     return bounds;
 }
Exemplo n.º 7
0
 public void Render(Canvas c, Paint p)
 {
     c.DrawBitmap(_bubble, _x, _y, p);
     p.Color = _color;
     p.TextSize = _textSize;
     p.AntiAlias = true;
     c.DrawText ("Purr", _x + _bubble.Width / 2 - p.MeasureText("Purr") / 2, _y + _bubble.Height / 2 + _textSize / 4, p);
 }
 /**
  * Calculate the bounds for a view's title
  *
  * @param index
  * @param paint
  * @return
  */
 private Rect calcBounds(int index, Paint paint)
 {
     //Calculate the text bounds
     Rect bounds = new Rect();
     string title = getTitle(index);
     bounds.Right = (int)paint.MeasureText(title, 0, title.Length);
     bounds.Bottom = (int)(paint.Descent() - paint.Ascent());
     return bounds;
 }
Exemplo n.º 9
0
		/// <Docs>The Canvas to which the View is rendered.</Docs>
		/// <summary>
		/// Draw the specified canvas.
		/// </summary>
		/// <param name="canvas">Canvas to draw onto.</param>
		public override void Draw(Canvas canvas)
		{
			BadgeImage image = (BadgeImage)Element;

			// Set color of icon
			if (Control.Drawable != null)
			{
				if (image.Selected)
				{
					Control.Drawable.SetColorFilter(filterColor);
				}
				else
				{
					Control.Drawable.SetColorFilter(filterGray);
				}
			}

			base.Draw(canvas);

			if (image.Number > 0)
			{
				using (Paint paint = new Paint())
				{
					paint.Color = image.Selected ? Xamarin.Forms.Color.Red.ToAndroid() : Xamarin.Forms.Color.Gray.ToAndroid();
					paint.StrokeWidth = 0f;
					paint.SetStyle(Paint.Style.FillAndStroke);

					// Calc text size
					paint.TextSize = (int)this.DipToPixel(16);
					paint.FakeBoldText = true;

					string text = image.Number.ToString();
					Rect textBounds = new Rect(0, 0, 0, 0);

					paint.GetTextBounds(text, 0, text.Length, textBounds);

					float textWidth = paint.MeasureText(text);
					float textHeight = textBounds.Height();

					float badgeWidth = textWidth + this.DipToPixel(9);
					float badgeHeight = textHeight + this.DipToPixel(9);

					if (badgeWidth < badgeHeight)
					{
						badgeWidth = badgeHeight;
					}

					double offsetX = (image.Bounds.Width - image.Bounds.Width) / 2;
					double offsetY = (image.Bounds.Height - image.Bounds.Height) / 2;

					float left = this.DipToPixel(image.Bounds.Width) - badgeWidth;
					float top = 1;
					float right = left + badgeWidth;
					float bottom = top + badgeHeight;
					float radius = (badgeHeight / 2f) - 1f;

					using (Path path = new Path())
					{
						canvas.DrawRoundRect(new RectF(left, top, left + badgeWidth, top + badgeHeight), radius, radius, paint);

						paint.Color = Xamarin.Forms.Color.White.ToAndroid();

						canvas.DrawText(image.Number.ToString(), left + ((badgeWidth - textWidth) / 2) - 1, bottom - ((badgeHeight - textHeight) / 2), paint);
					}
				}
			}
		}
        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.º 11
0
        public override void Draw(Canvas canvas)
        {
            //Console.WriteLine("EqualizerPresetGraphView - Draw - Width: {0} Height: {1}", Width, Height);

            float padding = 6 * Resources.DisplayMetrics.Density;
            float heightAvailable = Height - (padding*2);            

            var paintRect = new Paint {
                AntiAlias = true,
                Color = Color.ParseColor("#222222")
            };
            paintRect.SetStyle(Paint.Style.Fill);
            canvas.DrawRect(new Rect(0, 0, Width, Height), paintRect);

            if (_preset == null)
                return;

            // Draw center line
            var paintCenterLine = new Paint {
                AntiAlias = true,
                Color = Color.DarkGray
            };
            paintCenterLine.SetStyle(Paint.Style.Fill);
            paintCenterLine.StrokeWidth = 2f;
            canvas.DrawLine(padding, Height / 2, Width - padding, Height / 2, paintCenterLine);

            // Draw 20Hz and 20kHz lines
            paintCenterLine.StrokeWidth = 1f;
            canvas.DrawLine(padding, padding, padding, Height - padding, paintCenterLine);
            canvas.DrawLine(Width - padding, padding, Width - padding, Height - padding, paintCenterLine);

            var paintText = new Paint {
                AntiAlias = true,
                Color = Color.Gray,
                TextSize = 14 * Resources.DisplayMetrics.Density
            };
            float textWidth = paintText.MeasureText(_preset.Bands[_preset.Bands.Count - 1].CenterString);
            canvas.DrawText(_preset.Bands[0].CenterString, padding * 2, Height - (padding * 2), paintText);
            canvas.DrawText(_preset.Bands[_preset.Bands.Count - 1].CenterString, Width - textWidth - (padding * 2), Height - (padding * 2), paintText);

            if (_preset == null)
                return;

            // Draw equalizer line
            var points = new List<float>();
            var paintEQLine = new Paint
            {
                AntiAlias = true,
                Color = Color.Yellow
            };
            paintEQLine.SetStyle(Paint.Style.Stroke);
            paintEQLine.StrokeWidth = 2f * Resources.DisplayMetrics.Density;
            float x = padding;
            for (int a = 0; a < _preset.Bands.Count; a++)
            {
                // Value range is -6 to 6.
                var band = _preset.Bands[a];
                //float ratio = (band.Gain + 6) / (padding * 2);
                float ratio = (band.Gain + 6f) / 12f;
                float y = padding + heightAvailable - (ratio * (Height - (padding * 2)));

                //Console.WriteLine("EqualizerPresetGraphView - Draw - Width: {0} Height: {1} ratio: {2} x: {3} y: {4} padding: {5} heightAvailable: {6}", Width, Height, ratio, x, y, padding, heightAvailable);
                points.Add(x);
                points.Add(y);

                // Add the same point a second time because Android needs start/end for each segment
                if (a > 0 && a < _preset.Bands.Count - 1)
                {
                    points.Add(x);
                    points.Add(y);
                }

                x += (Width - (padding * 2)) / (_preset.Bands.Count - 1);
            }
            canvas.DrawLines(points.ToArray(), paintEQLine);
        }
Exemplo n.º 12
0
 public Vector2 GetTextDimensions(string text, double maxWidth, double maxHeight)
 {
     Paint paint = new Paint();
     double minFontSize = maxHeight;
     paint.AntiAlias = true;
     paint.TextAlign = Android.Graphics.Paint.Align.Left;
     paint.TextSize = (float)minFontSize;
     if (paint.MeasureText(text) > maxWidth)
     {
         minFontSize = Math.Min(minFontSize, maxWidth / paint.MeasureText(text) * maxHeight);
     }
     return new Vector2(paint.MeasureText(text), minFontSize);
 }
Exemplo n.º 13
0
        public void DrawText(double x, double y, double width, double height, string text, Model.UI.Color textColor, Model.UI.TextAlignment alignment)
        {
            Paint paint = new Paint();
            switch (alignment)
            {
                case Model.UI.TextAlignment.Left:
                    paint.TextAlign = Android.Graphics.Paint.Align.Left;
                    break;
                case Model.UI.TextAlignment.Right:
                    paint.TextAlign = Android.Graphics.Paint.Align.Right;
                    break;
                case Model.UI.TextAlignment.Centered:
                    paint.TextAlign = Android.Graphics.Paint.Align.Center;
                    break;
                default:
                    break;
            }
            
            string[] lines = text.Split('\n');
            double minFontSize = height / lines.Length;
            paint.AntiAlias = true;
            paint.Color = new Android.Graphics.Color((byte)textColor.Red, (byte)textColor.Green, (byte)textColor.Blue, (byte)(textColor.Alpha * 255));
            foreach (string line in lines)
            {
                paint.TextSize = (float)(height/ lines.Length);
                if (paint.MeasureText(line) > width)
                {
                    minFontSize = Math.Min(minFontSize, width / paint.MeasureText(line) * (height / lines.Length));
                }
            }
            paint.TextSize = (float)minFontSize;
            for (int index = 0; index < lines.Length; index++)
            {
                canvas.DrawText(lines[index], (float)(x + (alignment == Model.UI.TextAlignment.Centered ? width / 2 : 0)), (float)(y + height - paint.Descent() - ((height / lines.Length) * (0.5 - index + lines.Length - 1) - paint.TextSize / 2)), paint);
            }

        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates and returns the text parameters for the given callout text area.
        /// </summary>
        /// <returns>
        /// A Pair<UIFont, SizeF> containing the font and text size.
        /// </returns>
        /// <param name='textRect'>
        /// The current text area of the callout.
        /// </param>
        /// <param name='text'>
        /// The text for which to calculate and create the parameters.
        /// </param>
        public static float GetTextParamsForCallout(RectangleF textRect, string text, Context context)
        {
            SizeF constrainSize = new SizeF (textRect.Width, 9999);
            Paint paint = new Paint (PaintFlags.AntiAlias);
            paint.TextSize = 18f;
            paint.SetTypeface (Typeface.Default);
            float height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);

            float minHeight = textRect.Height - 2f;

            if (height > minHeight) {

                do {
                    height -= 1f;
                    paint.TextSize = height;
                    height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);
                } while (height > textRect.Height);

            } else if (height < minHeight) {

                do {
                    height += 1f;
                    paint.TextSize = height;
                    height = ImageHelper.convertDpToPixel (paint.MeasureText (text), context);
                } while (height < minHeight);

            }//end if else

            return paint.TextSize;
        }