Beispiel #1
0
 protected override void OnDraw(Canvas canvas)
 {
     base.OnDraw(canvas);
     var paint = new Paint();
     paint.SetColor(Color);
     canvas.DrawCircle(Width / 2, Height / 2, Width / 2, paint);
 }
Beispiel #2
0
        public static void Draw(Canvas canvas, IViewport viewport, IStyle style, IFeature feature)
        {
            try
            {
                if (!feature.RenderedGeometry.ContainsKey(style)) feature.RenderedGeometry[style] = ToAndroidBitmap(feature.Geometry);
                var bitmap = (AndroidGraphics.Bitmap)feature.RenderedGeometry[style];
                
                var dest = WorldToScreen(viewport, feature.Geometry.GetBoundingBox());
                dest = new BoundingBox(
                    dest.MinX,
                    dest.MinY,
                    dest.MaxX,
                    dest.MaxY);

                var destination = RoundToPixel(dest);
                using (var paint = new Paint())
                {
                    canvas.DrawBitmap(bitmap, new Rect(0, 0, bitmap.Width, bitmap.Height), destination, paint);
                }

                DrawOutline(canvas, style, destination);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }

        }
		public CirclePageIndicator(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
		{
			//Load defaults from resources
			var res = Resources;
			int defaultPageColor = res.GetColor(Resource.Color.default_circle_indicator_page_color);
			int defaultFillColor = res.GetColor(Resource.Color.default_circle_indicator_fill_color);
			int defaultOrientation = res.GetInteger(Resource.Integer.default_circle_indicator_orientation);
			int defaultStrokeColor = res.GetColor(Resource.Color.default_circle_indicator_stroke_color);
			float defaultStrokeWidth = res.GetDimension(Resource.Dimension.default_circle_indicator_stroke_width);
			float defaultRadius = res.GetDimension(Resource.Dimension.default_circle_indicator_radius);
			bool defaultCentered = res.GetBoolean(Resource.Boolean.default_circle_indicator_centered);
			bool defaultSnap = res.GetBoolean(Resource.Boolean.default_circle_indicator_snap);

			//Retrieve styles attributes
			var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CirclePageIndicator, defStyle, Resource.Style.Widget_CirclePageIndicator);

			mCentered = a.GetBoolean(Resource.Styleable.CirclePageIndicator_vpiCentered, defaultCentered);
			mOrientation = a.GetInt(Resource.Styleable.CirclePageIndicator_vpiOrientation, defaultOrientation);
			mPaintPageFill = new Paint(PaintFlags.AntiAlias);
			mPaintPageFill.SetStyle(Paint.Style.Fill);
			mPaintPageFill.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_vpiPageColor, defaultPageColor);
			mPaintStroke = new Paint(PaintFlags.AntiAlias);
			mPaintStroke.SetStyle(Paint.Style.Stroke);
			mPaintFill = new Paint(PaintFlags.AntiAlias);
			mPaintFill.SetStyle(Paint.Style.Fill);
			mSnap = a.GetBoolean(Resource.Styleable.CirclePageIndicator_vpiSnap, defaultSnap);

			mRadius = a.GetDimension(Resource.Styleable.CirclePageIndicator_vpiRadius, defaultRadius);
			mPaintFill.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_vpiFillColor, defaultFillColor);
			mPaintStroke.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_vpiStrokeColor, defaultStrokeColor);
			mPaintStroke.StrokeWidth = a.GetDimension(Resource.Styleable.CirclePageIndicator_vpiStrokeWidth, defaultStrokeWidth);

			a.Recycle();

		}
		public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
			Bitmap finalBitmap;
			if (bitmap.Width != radius || bitmap.Height!= radius)
				finalBitmap = Bitmap.CreateScaledBitmap(bitmap, radius, radius,
					false);
			else
				finalBitmap = bitmap;
			Bitmap output = Bitmap.CreateBitmap(finalBitmap.Width,
				finalBitmap.Height, Bitmap.Config.Argb8888);
			Canvas canvas = new Canvas(output);

			 Paint paint = new Paint();
			Rect rect = new Rect(0, 0, finalBitmap.Width,
				finalBitmap.Height);

			paint.AntiAlias=true;
			paint.FilterBitmap=true;
			paint.Dither=true;
			canvas.DrawARGB(0, 0, 0, 0);
			paint.Color=Color.ParseColor("#BAB399");
			canvas.DrawCircle(finalBitmap.Width / 2 + 0.7f,
				finalBitmap.Height / 2 + 0.7f,
				finalBitmap.Width / 2 + 0.1f, paint);
			paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
			canvas.DrawBitmap(finalBitmap, rect, rect, paint);

			return output;
		}	
		public static Bitmap ToCropped(Bitmap source, double zoomFactor, double xOffset, double yOffset, double cropWidthRatio, double cropHeightRatio)
		{
			double sourceWidth = source.Width;
			double sourceHeight = source.Height;

			double desiredWidth = sourceWidth;
			double desiredHeight = sourceHeight;

			double desiredRatio = cropWidthRatio / cropHeightRatio;
			double currentRatio = sourceWidth / sourceHeight;

			if (currentRatio > desiredRatio)
				desiredWidth = (cropWidthRatio * sourceHeight / cropHeightRatio);
			else if (currentRatio < desiredRatio)
				desiredHeight = (cropHeightRatio * sourceWidth / cropWidthRatio);

			xOffset = xOffset * desiredWidth;
			yOffset = yOffset * desiredHeight;

			desiredWidth =  desiredWidth / zoomFactor;
			desiredHeight = desiredHeight / zoomFactor;

			float cropX = (float)(((sourceWidth - desiredWidth) / 2) + xOffset);
			float cropY = (float)(((sourceHeight - desiredHeight) / 2) + yOffset);

			if (cropX < 0)
				cropX = 0;

			if (cropY < 0)
				cropY = 0;

			if (cropX + desiredWidth > sourceWidth)
				cropX = (float)(sourceWidth - desiredWidth);

			if (cropY + desiredHeight > sourceHeight)
				cropY = (float)(sourceHeight - desiredHeight);

			Bitmap bitmap = Bitmap.CreateBitmap((int)desiredWidth, (int)desiredHeight, source.GetConfig());

			using (Canvas canvas = new Canvas(bitmap))
			using (Paint paint = new Paint())
			using (BitmapShader shader = new BitmapShader(source, Shader.TileMode.Clamp, Shader.TileMode.Clamp))
			using (Matrix matrix = new Matrix())
			{
				if (cropX != 0 || cropY != 0)
				{
					matrix.SetTranslate(-cropX, -cropY);
					shader.SetLocalMatrix(matrix);
				}

				paint.SetShader(shader);
				paint.AntiAlias = false;

				RectF rectF = new RectF(0, 0, (int)desiredWidth, (int)desiredHeight);
				canvas.DrawRect(rectF, paint);

				return bitmap;				
			}
		}
 public CircleDrawable(Bitmap bmp)
 {
     this.bmp = bmp;
     this.bmpShader = new BitmapShader(bmp, Shader.TileMode.Clamp, Shader.TileMode.Clamp);
     this.paint = new Paint() { AntiAlias = true };
     this.paint.SetShader(bmpShader);
     this.oval = new RectF();
 }
Beispiel #7
0
 private static void DrawRectangle(Canvas canvas, RectF destination, Styles.Color outlineColor)
 {
     var paint = new Paint();
     paint.SetStyle(Paint.Style.Stroke);
     paint.Color = new AndroidColor(outlineColor.R, outlineColor.G, outlineColor.B, outlineColor.A);
     paint.StrokeWidth = 4;
     canvas.DrawRect(destination, paint);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CanvasRenderContext" /> class.
 /// </summary>
 /// <param name="scale">The scale.</param>
 public CanvasRenderContext(double scale)
 {
     this.paint = new Paint();
     this.path = new Path();
     this.bounds = new Rect();
     this.pts = new List<float>();
     this.Scale = scale;
 }
Beispiel #9
0
		public object Create(Color color)
		{
			var result = new ag.Paint
			{
				Color = color.ToAndroid(),
			};
			result.SetStyle(ag.Paint.Style.Fill);
			return result;
		}
		public object Create(Color startColor, Color endColor, PointF startPoint, PointF endPoint)
		{
			var shader = new ag.LinearGradient(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y, startColor.ToAndroid(), endColor.ToAndroid(), 
				// is this correct?
				ag.Shader.TileMode.Clamp);
			var paint = new ag.Paint();
			paint.SetShader(shader);
			return new BrushObject { Paint = paint }; // TODO: initial matrix
		}
			void InitStepCountPaint()
			{
				stepcountPaint = new Paint();
				//stepcountPaint.Color = Color.White;
				stepcountPaint.SetARGB(255, 50, 151, 218);
				stepcountPaint.SetTypeface(Typeface.Create(Typeface.SansSerif, TypefaceStyle.Normal));
				stepcountPaint.AntiAlias = true;
				stepcountPaint.TextSize = owner.Resources.GetDimension(Resource.Dimension.StepCountTextSize);
			}
		/// <summary>
		/// Initializes a new instance of the <see cref="ChartSurface"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="chart">The chart.</param>
		/// <param name="color">The color.</param>
		/// <param name="colors">The colors.</param>
		public ChartSurface(Context context, Chart chart, AndroidColor color, AndroidColor[] colors)
			: base(context)
		{
			SetWillNotDraw(false);

			Chart = chart;
			Paint = new Paint() { Color = color, StrokeWidth = 2 };
			Colors = colors;
		}
 public KenBurnsDrawable(Color defaultColor)
 {
     this.defaultColor = defaultColor;
     this.paint = new Paint
     {
         AntiAlias = false,
         FilterBitmap = false
     };
 }
 private void ShowPath(Canvas canvas, int x, int y, Path.FillType ft, Paint paint)
 {
     canvas.Save();
     canvas.Translate(x, y);
     canvas.ClipRect(0, 0, 120, 120);
     canvas.DrawColor(Color.White);
     mPath.SetFillType(ft);
     canvas.DrawPath(mPath, paint);
     canvas.Restore();
 }
        private static void ApplyCustomTypeface(Paint paint, Typeface tf, TypefaceStyle style, int size)
        {
            if (style == TypefaceStyle.Italic)
                paint.TextSkewX = -0.25f;

            if(size > 0)
                paint.TextSize = size;

            paint.SetTypeface (tf);
        }
Beispiel #16
0
		public object Create(Color color, float thickness)
		{
			var paint = new ag.Paint 
			{ 
				Color = color.ToAndroid(), 
				StrokeWidth = thickness,
				StrokeCap = ag.Paint.Cap.Square,
				StrokeMiter = 10f
			};
			return paint;
		}
 public static Bitmap ConvertConfig(Bitmap bitmap, Bitmap.Config config)
 {
     if (bitmap.GetConfig().Equals(config))
         return Bitmap.CreateBitmap(bitmap);
     Bitmap convertedBitmap = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, config);
     Canvas canvas = new Canvas(convertedBitmap);
     Android.Graphics.Paint paint = new Android.Graphics.Paint();
     paint.Color = Android.Graphics.Color.Black;
     canvas.DrawBitmap(bitmap, 0, 0, paint);
     return convertedBitmap;
 }
 private void Init()
 {
     IsRunning = false;
     OutlineAlpha = 1.0f;
     outlinePaint = new Paint();
     outlinePaint.AntiAlias = true;
     outlinePaint.StrokeWidth = Utils.Dp2Px(2);
     outlinePaint.Color = Resources.GetColor(Resource.Color.holo_blue);
     outlinePaint.SetStyle(Paint.Style.Stroke);
     var padding = Utils.Dp2Px(10);
     SetPadding(padding, padding, padding, padding);
 }
Beispiel #19
0
 private static Paint ToAndroid(this Pen pen)
 {
     var paint = new Paint
     {
         AntiAlias = true,
         Color = pen.Color.ToAndroid(),
         StrokeWidth = (float)pen.Width,
         StrokeJoin = Paint.Join.Round
     };
     paint.SetStyle(Paint.Style.Stroke);
     return paint;
 }
        public override void Draw(Canvas canvas, ICharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)
        {
            PrepView();

            canvas.Save();

            //Centering the token looks like a better strategy that aligning the bottom
            int padding = (bottom - top - View.Bottom) / 2;
            canvas.Translate(x, bottom - View.Bottom - padding);
            View.Draw(canvas);
            canvas.Restore();
        }
        public CircleView(Context context, int width, int height, int offset): base(context)
        {
            var paint = new Paint();
            paint.Color = Color.Red;
            paint.SetStyle(Paint.Style.Stroke);
            paint.StrokeWidth = 3;

            _shape = new ShapeDrawable(new OvalShape());
            _shape.Paint.Set(paint);

            _shape.SetBounds(offset, offset, width-offset, height-offset);
        }
Beispiel #22
0
        public MyOvalShape(Context context)
            : base(context)
        {
            var paint = new Paint();
            paint.SetARGB(255, 200, 255, 0);
            paint.SetStyle(Paint.Style.Stroke);
            paint.StrokeWidth = 4;

            _shape = new ShapeDrawable(new OvalShape());
            _shape.Paint.Set(paint);

            _shape.SetBounds(20, 20, 300, 200);
        }
Beispiel #23
0
        public ClingDrawer(Resources resources, Color showcaseColor)
        {
            this.showcaseColor = showcaseColor;

            PorterDuffXfermode mBlender = new PorterDuffXfermode(PorterDuff.Mode.Clear);
            mEraser = new Paint();
            mEraser.Color = Color.White;
            mEraser.Alpha = 0;
            mEraser.SetXfermode(mBlender);
            mEraser.AntiAlias = true;

            mShowcaseDrawable = resources.GetDrawable(Resource.Drawable.cling_bleached);
            mShowcaseDrawable.SetColorFilter(showcaseColor, PorterDuff.Mode.Multiply);
        }
 public override int GetSize(Paint paint, ICharSequence text, int start, int end, Paint.FontMetricsInt fm)
 {
     LocalPaint.Set(paint);
     ApplyCustomTypeFace(LocalPaint, _typeface);
     LocalPaint.GetTextBounds(_icon, 0, 1, TextBounds);
     if (fm != null)
     {
         fm.Descent = (int) (TextBounds.Height()*BaselineRatio);
         fm.Ascent = -(TextBounds.Height() - fm.Descent);
         fm.Top = fm.Ascent;
         fm.Bottom = fm.Descent;
     }
     return TextBounds.Width();
 }
        protected override void DispatchDraw(
            global::Android.Graphics.Canvas canvas)
        {
//            var gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0, 
//                               this.StartColor.ToAndroid(),
//                               this.EndColor.ToAndroid(),
//                               Android.Graphics.Shader.TileMode.Mirror);
            var gradient = new RadialGradient(-100, 1200, 3000, this.StartColor.ToAndroid(), this.EndColor.ToAndroid(), Android.Graphics.Shader.TileMode.Clamp);//(-50, -50, this.StartColor.ToAndroid(), this.EndColor.ToAndroid());
            var paint = new Android.Graphics.Paint() {
                Dither = true,
            };
            paint.SetShader(gradient);
            canvas.DrawPaint(paint);
            base.DispatchDraw(canvas);
        }
        public override void Draw(Canvas canvas)
        {
            var box = Element as RoundedBox;
            var rect = new Rect();
            var paint = new Paint() {
                Color = box.BackgroundColor.ToAndroid(),
                AntiAlias = true,
            };

            GetDrawingRect(rect);

            var radius = (float)(rect.Width() / box.Width * box.CornerRadius);

            canvas.DrawRoundRect(new RectF(rect), radius, radius, paint);
        }
 public BadgeDrawable(Drawable child)
 {
     this.child = child;
     badgePaint = new Paint
     {
         AntiAlias = true,
         Color = Color.Blue,
     };
     textPaint = new Paint
     {
         AntiAlias = true,
         Color = Android.Graphics.Color.White,
         TextSize = 16,
         TextAlign = Paint.Align.Center
     };
 }
 public static Bitmap GetRoundedCornerBitmap(this Bitmap bitmap, int? roundPixelSize = null)
 {
     var chooseSize = bitmap.Width > bitmap.Height ? bitmap.Height : bitmap.Width;
     roundPixelSize = roundPixelSize ?? (int)Application.Context.Resources.GetDimension(Resource.Dimension.RoundedCorners);
     var output = Bitmap.CreateBitmap(chooseSize, chooseSize, Bitmap.Config.Argb8888);
     var canvas = new Canvas(output);
     var paint = new Paint();
     var rect = new Rect(0, 0, chooseSize, chooseSize);
     var rectF = new RectF(rect);
     var roundPx = roundPixelSize.Value;
     paint.AntiAlias = true;
     canvas.DrawRoundRect(rectF, roundPx, roundPx, paint);
     paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
     canvas.DrawBitmap(bitmap, rect, rect, paint);
     return output;
 }
        // ---------------------------------------------------------

        #region Overrides

        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                _formsView = (Paint.Views.PaintView.PaintView)e.NewElement;

                _currentPaint = new Android.Graphics.Paint();
                _currentPaint.Dither = true;
                _currentPaint.SetStyle(Android.Graphics.Paint.Style.Stroke);
                _currentPaint.StrokeJoin = Android.Graphics.Paint.Join.Round;
                _currentPaint.StrokeCap = Android.Graphics.Paint.Cap.Round;

                _deviceDensity = AndroidDevice.DisplayMetrics.Density > 1 ? AndroidDevice.DisplayMetrics.Density : 1;
            }
        }
            public override void Draw(Android.Graphics.Canvas canvas,
                MapView mapView, bool shadow)
            {
                base.Draw(canvas, mapView, shadow);

                var paint = new Paint();
                paint.AntiAlias = true;
                paint.Color = Color.Purple;
                paint.Alpha = 127;

                var gp = new GeoPoint((int)(29.97611 * 1e6), (int)(31.132778 * 1e6));
                var pt = mapView.Projection.ToPixels(gp, null);
                float distance = mapView.Projection.MetersToEquatorPixels(200);

                canvas.DrawCircle(pt.X, pt.Y, distance/2, paint);

            }
Beispiel #31
0
        void SetBackground(APaint platformPaint)
        {
            if (platformPaint != null)
            {
                if (_backgroundColor != null)
#pragma warning disable CA1416 // https://github.com/xamarin/xamarin-android/issues/6962
                {
                    platformPaint.Color = _backgroundColor.Value;
                }
#pragma warning restore CA1416
                else
                {
                    if (_background != null)
                    {
                        SetPaint(platformPaint, _background);
                    }
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// Read the file and draw rectangles on it.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="annotations">Annotations to be add to the image. Can consist of rectangles and labels</param>
        /// <returns>The image in Jpeg stream format</returns>
        public static Emgu.Models.JpegData ImageFileToJpeg(String fileName, Annotation[] annotations = null)
        {
            using (BitmapFactory.Options options = new BitmapFactory.Options())
            {
                options.InMutable = true;
                using (Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options))
                {
                    if (annotations != null)
                    {
                        using (Android.Graphics.Paint p = new Android.Graphics.Paint())
                            using (Canvas c = new Canvas(bmp))
                            {
                                p.AntiAlias = true;
                                p.Color     = Android.Graphics.Color.Red;

                                p.TextSize = 20;
                                for (int i = 0; i < annotations.Length; i++)
                                {
                                    p.SetStyle(Paint.Style.Stroke);
                                    float[] rects           = ScaleLocation(annotations[i].Rectangle, bmp.Width, bmp.Height);
                                    Android.Graphics.Rect r = new Rect((int)rects[0], (int)rects[1], (int)rects[2],
                                                                       (int)rects[3]);
                                    c.DrawRect(r, p);

                                    p.SetStyle(Paint.Style.Fill);
                                    c.DrawText(annotations[i].Label, (int)rects[0], (int)rects[1], p);
                                }
                            }
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                        JpegData result = new JpegData();
                        result.Raw    = ms.ToArray();
                        result.Width  = bmp.Width;
                        result.Height = bmp.Height;
                        return(result);
                    }
                }
            }
        }
Beispiel #33
0
        public static void DrawResults(Android.Graphics.Bitmap bmp, MultiboxGraph.Result result, float scoreThreshold)
        {
            Rectangle[] locations = ScaleLocation(result.DecodedLocations, bmp.Width, bmp.Height);

            Android.Graphics.Paint p = new Android.Graphics.Paint();
            p.SetStyle(Paint.Style.Stroke);
            p.AntiAlias = true;
            p.Color     = Android.Graphics.Color.Red;
            Canvas c = new Canvas(bmp);


            for (int i = 0; i < result.Scores.Length; i++)
            {
                if (result.Scores[i] > scoreThreshold)
                {
                    Rectangle             rect = locations[result.Indices[i]];
                    Android.Graphics.Rect r    = new Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
                    c.DrawRect(r, p);
                }
            }
        }
        public override void Draw(Canvas canvas)
        {
            base.Draw(canvas);



            var gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0, this.StartColor.ToAndroid(), this.EndColor.ToAndroid(), Android.Graphics.Shader.TileMode.Mirror);



            var paint = new Android.Graphics.Paint()
            {
                Dither    = true,
                AntiAlias = true
            };

            paint.SetShader(gradient);
            var rect = new RectF(0, 0, canvas.Width, canvas.Height);

            canvas.DrawRoundRect(rect, 00f, 00f, paint); // set CornerRadius  here
        }
        protected override void DispatchDraw(Canvas canvas)
        {
            base.DispatchDraw(canvas);
            LinearGradient gradient = null;

            //for horizontal gradient
            if (((GradientFrame)Element).GradientColorOrientation == GradientFrame.GradientOrientation.Horizontal)
            {
                gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0,



                     ((GradientFrame)Element).StartColor.ToAndroid(),
                     ((GradientFrame)Element).EndColor.ToAndroid(),

                     Android.Graphics.Shader.TileMode.Mirror);

            }
            //for vertical gradient
            if (((GradientFrame)Element).GradientColorOrientation == GradientFrame.GradientOrientation.Vertical)
            {
                gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,



                     ((GradientFrame)Element).StartColor.ToAndroid(),
                     ((GradientFrame)Element).EndColor.ToAndroid(),

                     Android.Graphics.Shader.TileMode.Mirror);

            }

            var paint = new Android.Graphics.Paint()
            {
                Dither = true,
            };
            paint.SetShader(gradient);
            canvas.DrawPaint(paint);
            base.DispatchDraw(canvas);
        }
Beispiel #36
0
        private void Start()
        {
            CurrentLineColor = Color.Black;
            PenWidth         = 5.0f;

            DrawPath  = new Android.Graphics.Path();
            DrawPaint = new Android.Graphics.Paint
            {
                Color       = CurrentLineColor,
                AntiAlias   = true,
                StrokeWidth = PenWidth
            };

            DrawPaint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            DrawPaint.StrokeJoin = Android.Graphics.Paint.Join.Round;
            DrawPaint.StrokeCap  = Android.Graphics.Paint.Cap.Round;

            CanvasPaint = new Android.Graphics.Paint
            {
                Dither = true
            };
        }
Beispiel #37
0
        protected override void DispatchDraw(Canvas canvas)
        {
            LinearGradient gradient = null;

            gradient = new Android.Graphics.LinearGradient(
                0,
                0,
                Width,
                0,
                ((GradientButton)Element).StartColor.ToAndroid(),
                ((GradientButton)Element).EndColor.ToAndroid(),
                Android.Graphics.Shader.TileMode.Mirror);

            var paint = new Android.Graphics.Paint()
            {
                Dither = true,
            };

            paint.SetShader(gradient);
            canvas.DrawPaint(paint);
            base.DispatchDraw(canvas);
        }
        public Android.Graphics.Bitmap ToGrayscale(Android.Graphics.Bitmap bmpOriginal)
        {
            int width, height;

            height = bmpOriginal.Height;
            width  = bmpOriginal.Width;

            float[] mat = new float[] {
                0.3f, 0.59f, 0.11f, 0, 0,
                0.3f, 0.59f, 0.11f, 0, 0,
                0.3f, 0.59f, 0.11f, 0, 0,
                0, 0, 0, 1, 0,
            };

            Android.Graphics.Bitmap bmpGrayscale = Android.Graphics.Bitmap.CreateBitmap(width, height, Android.Graphics.Bitmap.Config.Argb8888);
            GC.Collect();
            Android.Graphics.Canvas c = new Android.Graphics.Canvas(bmpGrayscale);
            Android.Graphics.ColorMatrixColorFilter filter = new Android.Graphics.ColorMatrixColorFilter(mat);
            Android.Graphics.Paint paint = new Android.Graphics.Paint();
            paint.SetColorFilter(filter);
            c.DrawBitmap(bmpOriginal, 0, 0, paint);
            return(bmpGrayscale);
        }
        private void DrawFocusRect(ISurfaceHolder holder, float RectLeft, float RectTop, float RectRight, float RectBottom, Android.Graphics.Color color)
        {
            //lock
            var canvas = holder.LockCanvas();

            //no pointer to canvas?
            if (canvas == null)
            {
                return;
            }

            //detect face
            FaceEyes FE = Detect();

            //clear out
            canvas.DrawColor(Android.Graphics.Color.Transparent, Android.Graphics.PorterDuff.Mode.Clear);

            //border's properties
            var paint = new Android.Graphics.Paint();

            paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            paint.Color       = color;
            paint.StrokeWidth = 3;

            Rectangle e0 = FE.Eyes[0];
            Rectangle e1 = FE.Eyes[1];
            Rectangle f0 = FE.Faces[0];

            canvas.DrawRect(new Rect(e0.Left, e0.Top, e0.Right, e0.Bottom), paint);
            canvas.DrawRect(new Rect(e1.Left, e1.Top, e1.Right, e1.Bottom), paint);
            paint.Color = Android.Graphics.Color.White;
            canvas.DrawRect(new Rect(f0.Left, f0.Top, f0.Right, f0.Bottom), paint);

            //unlock
            holder.UnlockCanvasAndPost(canvas);
        }
Beispiel #40
0
 public void FillEllipse(Paint b, Rectangle rectangle)
 {
     // TODO
 }
Beispiel #41
0
 public void FillEllipse(Paint b, float x, float y, float widht, float height)
 {
     // TODO
 }
Beispiel #42
0
 public void DrawRectangle(Paint p, Rectangle rect)
 {
     this.DrawRectangle(p, rect.X, rect.Y, rect.Width, rect.Height);
 }
Beispiel #43
0
 public void FillRectangle(Paint p, float x, float y, float width, float height)
 {
     p.SetStyle(Paint.Style.Fill);
     this.canvas.DrawRect(x, y, x + width, y + height, p);
 }
Beispiel #44
0
 public void DrawEllipse(Paint pen, Rectangle rectangle)
 {
     // TODO
 }
Beispiel #45
0
        protected override void OnDraw(Canvas canvas)
        {
            coreX       = Width / 2;
            coreY       = Height / 2;
            roundRadius = (int)(Width / 2 * radiusDistance); //计算中心圆圈半径

            RectF rect = new RectF(0, 0, Width, Height);

            if (roundMenus != null && roundMenus.Count > 0)
            {
                float sweepAngle = 360 / roundMenus.Count; //每个弧形的角度
                deviationDegree = sweepAngle / 2;          //其实的偏移角度,如果4个扇形的时候是X形状,而非+,设为0试试就知道什么意思了
                for (int i = 0; i < roundMenus.Count; i++)
                {
                    RoundMenu roundMenu = roundMenus[i];
                    //填充
                    Paint paint = new Paint();
                    paint.AntiAlias = true;
                    if (onClickState == i)
                    {
                        //选中
                        paint.Color = new Color(roundMenu.selectSolidColor);
                    }
                    else
                    {
                        //未选中
                        paint.Color = new Color(roundMenu.solidColor);
                    }
                    canvas.DrawArc(rect, deviationDegree + (i * sweepAngle), sweepAngle, true, paint);

                    //画描边
                    paint             = new Paint();
                    paint.AntiAlias   = true;
                    paint.StrokeWidth = roundMenu.strokeSize;
                    paint.SetStyle(Paint.Style.Stroke);
                    paint.Color = new Color(roundMenu.strokeColor);
                    canvas.DrawArc(rect, deviationDegree + (i * sweepAngle), sweepAngle, roundMenu.useCenter, paint);

                    //画图案
                    Matrix matrix = new Matrix();
                    matrix.PostTranslate((float)((coreX + Width / 2 * roundMenu.iconDistance) - (roundMenu.icon.Width / 2)), coreY - (roundMenu.icon.Height / 2));
                    matrix.PostRotate(((i + 1) * sweepAngle), coreX, coreY);
                    canvas.DrawBitmap(roundMenu.icon, matrix, null);
                }
            }

            //画中心圆圈
            if (isCoreMenu)
            {
                //填充
                RectF rect1 = new RectF(coreX - roundRadius, coreY - roundRadius, coreX + roundRadius, coreY + roundRadius);
                Paint paint = new Paint();
                paint.AntiAlias   = true;
                paint.StrokeWidth = coreMenuStrokeSize;
                if (onClickState == -1)
                {
                    paint.Color = new Color(coreMenuSelectColor);
                }
                else
                {
                    paint.Color = new Color(coreMenuColor);
                }
                canvas.DrawArc(rect1, 0, 360, true, paint);

                //画描边
                paint             = new Paint();
                paint.AntiAlias   = true;
                paint.StrokeWidth = coreMenuStrokeSize;
                paint.SetStyle(Paint.Style.Stroke);
                paint.Color = new Color(coreMenuStrokeColor);
                canvas.DrawArc(rect1, 0, 360, true, paint);
                if (coreBitmap != null)
                {
                    //画中心圆圈的"OK"图标
                    canvas.DrawBitmap(coreBitmap, coreX - coreBitmap.Width / 2, coreY - coreBitmap.Height / 2, null); //在 0,0坐标开始画入src
                }
            }
        }
 private Graphics()
 {
     this.paint     = new droid.Paint();
     this.Flags     = droid.PaintFlags.AntiAlias;
     this.ownCanvas = false;
 }
Beispiel #47
0
        public void Wrap(DroidTextLayoutBackend layout, AG.Paint paint)
        {
            var text = layout.Text;

            var metrics = paint.GetFontMetrics();

            Baseline   = -metrics.Top;
            LineHeight = -metrics.Ascent + metrics.Descent;
            LineY      = -metrics.Ascent;         //- (metrics.Ascent + metrics.Descent);

            var charWidths = new float[text.Length];

            paint.GetTextWidths(text, charWidths);

            var iLf = text.IndexOfAny(new char[] { '\n', '\r' });

            HasLineFeed = iLf >= 0;

            var textWidth = charWidths.Sum();

            if (!HasLineFeed && (layout.Height <= 0 || layout.Height <= LineHeight) && (layout.Width <= 0 || textWidth <= layout.Width))
            {
                LineWidth = textWidth;
                SingleLine(this);
            }
            else
            {
                MaxHeight = PreferedSize.Height > 0 ? PreferedSize.Height : (layout.Height <= 0 ? float.MaxValue : layout.Height);
                MaxWidth  = PreferedSize.Width > 0 ? PreferedSize.Width : (layout.Width <= 0 ? textWidth : layout.Width);

                CursorPos = 0;
                LineStart = 0;

                while (LineY <= MaxHeight && CursorPos < text.Length)
                {
                    LineWidth = 0f;
                    var whitePosY = -1f;
                    var whitepos  = -1;
                    var newLine   = false;

                    while (CursorPos < text.Length)
                    {
                        newLine = text [CursorPos] == '\n';

                        if (text [CursorPos] == '\r')
                        {
                            CursorPos++;
                            continue;
                        }

                        if (newLine)
                        {
                            break;
                        }

                        if (char.IsWhiteSpace(text [CursorPos]))
                        {
                            whitepos  = CursorPos;
                            whitePosY = LineWidth;
                        }
                        LineWidth += charWidths [CursorPos];

                        if (LineWidth > MaxWidth)
                        {
                            if (whitepos > 0)
                            {
                                CursorPos = whitepos;
                                LineWidth = whitePosY;
                            }
                            break;
                        }
                        CursorPos++;
                    }

                    Action line = () => {
                        MultiLine(this);
                        LineY += LineHeight;
                    };

                    line();

                    CursorPos++;
                    LineStart = CursorPos;

                    if (newLine && CursorPos == text.Length)
                    {
                        line();
                    }
                }
            }
        }
        protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime)
        {
            var box = (GradientContentView)Element;
            //var radius = Math.Min(box.Width, Height) / 2;
            //var strokeWidth = 10;
            //radius -= strokeWidth / 2;

            ////Create path to clip
            //var path = new Path();
            //path.AddRoundRect(0,0,0,0, (float)box.Width, (float)box.Height, Path.Direction.Ccw);
            //canvas.Save();
            //canvas.ClipPath(path);

            //var result = base.DrawChild(canvas, child, drawingTime);

            //canvas.Restore();

            //canvas.S
            //// Create path for circle border
            //path = new Path();
            //path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);

            ////var paint = new Paint();
            ////paint.AntiAlias = true;
            ////paint.StrokeWidth = 5;
            ////paint.SetStyle(Paint.Style.Stroke);
            ////paint.Color = Android.Graphics.Color.ParseColor(((ImageCircle)Element).BorderColor);

            //canvas.DrawPath(path, paint);

            ////Properly dispose
            //paint.Dispose();
            //path.Dispose();
            //return result;

            //var path = new RoundRectShape(new float[] { 8, 8, 8, 8, 8, 8, 8, 8 }, null, null);
            var path = new Path();

            path.AddRoundRect(new RectF(0, 0, Width, Height), box.CornerRadius, box.CornerRadius, Path.Direction.Ccw);
            double width  = 0;
            double height = 0;

            if (box.Orientation == GradientOrientation.Horizontal)
            {
                width = Width;
            }
            else
            {
                height = Height;
            }
            // var gradientDrawable =  new GradientDrawable(GradientDrawable.Orientation.BlTr, );

            //var gradient = new Android.Graphics.LinearGradient((float)box.StartPointX, (float)box.StartPointY, (float)box.EndPointX, (float)box.EndPointY,
            float StartPointX, StartPointY, EndPointX, EndPointY = 0;

            StartPointX = ((float)Width * (float)box.StartPointX);
            StartPointY = ((float)Height * (float)box.StartPointY);
            EndPointX   = ((float)Width * (float)box.EndPointX);
            EndPointY   = ((float)Height * (float)box.EndPointY);

            //var gradient = new Android.Graphics.LinearGradient((float)box.StartPointX, (float)box.StartPointY, (float)width, (float)height,
            var gradient = new Android.Graphics.LinearGradient(StartPointX, StartPointY, EndPointX, EndPointY,

                                                               box.StartColor.ToAndroid(),
                                                               box.EndColor.ToAndroid(),
                                                               Android.Graphics.Shader.TileMode.Clamp);

            var paint = new Android.Graphics.Paint()
            {
                Dither = true,
            };



            paint.SetShader(gradient);
            canvas.DrawPath(path, paint);

            // canvas.DrawPath();

            //GradientDrawable.Bounds = canvas.ClipBounds;
            //GradientDrawable.SetOrientation(GradientContentView.Orientation == GradientOrientation.Vertical
            //    ? GradientDrawable.Orientation.TopBottom
            //    : GradientDrawable.Orientation.LeftRight);
            //GradientDrawable.Draw(canvas);



            return(base.DrawChild(canvas, child, drawingTime));
        }
        private void CustomDispatchDraw(Canvas canvas)
        {
            try
            {
                this.StartColor    = stack.StartColor;
                this.EndColor      = stack.EndColor;
                this.gradientStyle = stack.GradientDirection;
                if (_path != null)
                {
                    int height = Height;
                    int width  = Width;

                    if (gradientStyle == GradientStyle.Vertical)
                    {
                        width = 0;
                    }
                    else if (gradientStyle == GradientStyle.Horizontal)
                    {
                        height = 0;
                    }
                    else
                    {
                        height = 0;
                    }

                    var gradient = new Android.Graphics.LinearGradient(0, 0, width, height, this.StartColor.ToAndroid(), this.EndColor.ToAndroid(), Android.Graphics.Shader.TileMode.Mirror);
                    var paint    = new Android.Graphics.Paint()
                    {
                        Dither = true,
                    };

                    paint.SetShader(gradient);
                    canvas.Save();
                    canvas.ClipPath(_path);
                    canvas.DrawPaint(paint);
                    try
                    {
                        if (stack.HasBorderColor == true)
                        {
                            var borderPaint = new Paint();
                            borderPaint.AntiAlias   = true;
                            borderPaint.StrokeWidth = 2;
                            borderPaint.SetStyle(Paint.Style.Stroke);
                            borderPaint.Color = stack.BorderColor.ToAndroid();//global::Android.Graphics.Color.White;
                            canvas.DrawPath(_path, borderPaint);
                        }
                    }
                    catch (Exception ex)
                    {
                        var msg = ex.Message + "\n" + ex.StackTrace;
                        System.Diagnostics.Debug.WriteLine(msg);
                    }
                    canvas.Restore();
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message + "\n" + ex.StackTrace;
                System.Diagnostics.Debug.WriteLine(msg);
            }
        }
Beispiel #50
0
        /// <summary>
        /// Read the file and draw rectangles on it.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="annotations">Annotations to be add to the image. Can consist of rectangles and lables</param>
        /// <returns>The image in Jpeg stream format</returns>
        public static JpegData ImageFileToJpeg(String fileName, Annotation[] annotations = null)
        {
#if __ANDROID__
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InMutable = true;
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options);

            Android.Graphics.Paint p = new Android.Graphics.Paint();
            p.SetStyle(Paint.Style.Stroke);
            p.AntiAlias = true;
            p.Color     = Android.Graphics.Color.Red;
            Canvas c = new Canvas(bmp);

            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects           = ScaleLocation(annotations[i].Rectangle, bmp.Width, bmp.Height);
                Android.Graphics.Rect r = new Rect((int)rects[0], (int)rects[1], (int)rects[2], (int)rects[3]);
                c.DrawRect(r, p);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                JpegData result = new JpegData();
                result.Raw    = ms.ToArray();
                result.Width  = bmp.Width;
                result.Height = bmp.Height;
                return(result);
            }
#elif __MACOS__
            NSImage img = NSImage.ImageNamed(fileName);

            if (annotations != null && annotations.Length > 0)
            {
                DrawAnnotations(img, annotations);
            }

            var    imageData = img.AsTiff();
            var    imageRep  = NSBitmapImageRep.ImageRepsWithData(imageData)[0] as NSBitmapImageRep;
            var    jpegData  = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, null);
            byte[] jpeg      = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);

            JpegData result = new JpegData();
            result.Raw    = jpeg;
            result.Width  = (int)img.Size.Width;
            result.Height = (int)img.Size.Height;

            return(result);
#elif __IOS__
            UIImage uiimage = new UIImage(fileName);

            UIGraphics.BeginImageContextWithOptions(uiimage.Size, false, 0);
            var context = UIGraphics.GetCurrentContext();

            uiimage.Draw(new CGPoint());
            context.SetStrokeColor(UIColor.Red.CGColor);
            context.SetLineWidth(2);

            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects = ScaleLocation(
                    annotations[i].Rectangle,
                    (int)uiimage.Size.Width,
                    (int)uiimage.Size.Height);
                CGRect cgRect = new CGRect(
                    (nfloat)rects[0],
                    (nfloat)rects[1],
                    (nfloat)(rects[2] - rects[0]),
                    (nfloat)(rects[3] - rects[1]));
                context.AddRect(cgRect);
                context.DrawPath(CGPathDrawingMode.Stroke);
            }
            context.ScaleCTM(1, -1);
            context.TranslateCTM(0, -uiimage.Size.Height);
            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects = ScaleLocation(
                    annotations[i].Rectangle,
                    (int)uiimage.Size.Width,
                    (int)uiimage.Size.Height);
                context.SelectFont("Helvetica", 18, CGTextEncoding.MacRoman);
                context.SetFillColor((nfloat)1.0, (nfloat)0.0, (nfloat)0.0, (nfloat)1.0);
                context.SetTextDrawingMode(CGTextDrawingMode.Fill);
                context.ShowTextAtPoint(rects[0], uiimage.Size.Height - rects[1], annotations[i].Label);
            }
            UIImage imgWithRect = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            var    jpegData = imgWithRect.AsJPEG();
            byte[] jpeg     = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);
            JpegData result = new JpegData();
            result.Raw    = jpeg;
            result.Width  = (int)uiimage.Size.Width;
            result.Height = (int)uiimage.Size.Height;
            return(result);
#else
            Bitmap img = new Bitmap(fileName);

            if (annotations != null)
            {
                using (Graphics g = Graphics.FromImage(img))
                {
                    for (int i = 0; i < annotations.Length; i++)
                    {
                        if (annotations[i].Rectangle != null)
                        {
                            float[]    rects  = ScaleLocation(annotations[i].Rectangle, img.Width, img.Height);
                            PointF     origin = new PointF(rects[0], rects[1]);
                            RectangleF rect   = new RectangleF(origin, new SizeF(rects[2] - rects[0], rects[3] - rects[1]));
                            Pen        redPen = new Pen(Color.Red, 3);
                            g.DrawRectangle(redPen, Rectangle.Round(rect));

                            String label = annotations[i].Label;
                            if (label != null)
                            {
                                g.DrawString(label, new Font(FontFamily.GenericSansSerif, 20f), Brushes.Red, origin);
                            }
                        }
                    }
                    g.Save();
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                JpegData result = new JpegData();
                result.Raw    = ms.ToArray();
                result.Width  = img.Size.Width;
                result.Height = img.Size.Height;
                return(result);
            }
#endif
        }
Beispiel #51
0
        public static void UpdateBackground(this Paint paint, Brush brush, int height, int width)
        {
            if (paint == null || brush == null || brush.IsEmpty)
            {
                return;
            }

            if (brush is SolidColorBrush solidColorBrush)
            {
                var backgroundColor = solidColorBrush.Color;
                paint.Color = backgroundColor.ToAndroid();
            }

            if (brush is LinearGradientBrush linearGradientBrush)
            {
                var p1 = linearGradientBrush.StartPoint;
                var x1 = (float)p1.X;
                var y1 = (float)p1.Y;

                var p2 = linearGradientBrush.EndPoint;
                var x2 = (float)p2.X;
                var y2 = (float)p2.Y;

                var gradientBrushData = linearGradientBrush.GetGradientBrushData();
                var colors            = gradientBrushData.Item1;
                var offsets           = gradientBrushData.Item2;

                if (colors.Length < 2)
                {
                    return;
                }

                var linearGradientShader = new LinearGradient(
                    width * x1,
                    height * y1,
                    width * x2,
                    height * y2,
                    colors,
                    offsets,
                    Shader.TileMode.Clamp);

                paint.SetShader(linearGradientShader);
            }

            if (brush is RadialGradientBrush radialGradientBrush)
            {
                var   center  = radialGradientBrush.Center;
                float centerX = (float)center.X;
                float centerY = (float)center.Y;
                float radius  = (float)radialGradientBrush.Radius;

                var gradientBrushData = radialGradientBrush.GetGradientBrushData();
                var colors            = gradientBrushData.Item1;
                var offsets           = gradientBrushData.Item2;

                if (colors.Length < 2)
                {
                    return;
                }

                var radialGradientShader = new RadialGradient(
                    width * centerX,
                    height * centerY,
                    Math.Max(height, width) * radius,
                    colors,
                    offsets,
                    Shader.TileMode.Clamp);

                paint.SetShader(radialGradientShader);
            }
        }
Beispiel #52
0
 public void DrawLine(Paint p, float x1, float y1, float x2, float y2)
 {
     this.canvas.DrawLine(x1, y1, x2, y2, p);
 }
Beispiel #53
0
 public void DrawLine(Paint p, Point startPoint, Point endPoint)
 {
     this.canvas.DrawLine(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y, p);
 }
Beispiel #54
0
        /// <summary>
        /// Read the file and draw rectangles on it.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="annotations">Annotations to be add to the image. Can consist of rectangles and lables</param>
        /// <returns>The image in Jpeg stream format</returns>
        public static byte[] ImageFileToJpeg(String fileName, Annotation[] annotations = null)
        {
#if __ANDROID__
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InMutable = true;
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options);

            Android.Graphics.Paint p = new Android.Graphics.Paint();
            p.SetStyle(Paint.Style.Stroke);
            p.AntiAlias = true;
            p.Color     = Android.Graphics.Color.Red;
            Canvas c = new Canvas(bmp);

            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects           = ScaleLocation(annotations[i].Rectangle, bmp.Width, bmp.Height);
                Android.Graphics.Rect r = new Rect((int)rects[0], (int)rects[1], (int)rects[2], (int)rects[3]);
                c.DrawRect(r, p);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                return(ms.ToArray());
            }
#elif __MACOS__
            NSImage img = NSImage.ImageNamed(fileName);

            DrawAnnotations(img, annotations);

            /*
             * img.LockFocus();
             *
             * NSColor redColor = NSColor.Red;
             * redColor.Set();
             * var context = NSGraphicsContext.CurrentContext;
             * var cgcontext = context.CGContext;
             * cgcontext.ScaleCTM(1, -1);
             * cgcontext.TranslateCTM(0, -img.Size.Height);
             * //context.IsFlipped = !context.IsFlipped;
             * for (int i = 0; i < annotations.Length; i++)
             * {
             *  float[] rects = ScaleLocation(annotations[i].Rectangle, (int)img.Size.Width, (int) img.Size.Height);
             *  CGRect cgRect = new CGRect(
             *      rects[0],
             *      rects[1],
             *      rects[2] - rects[0],
             *      rects[3] - rects[1]);
             *  NSBezierPath.StrokeRect(cgRect);
             * }
             * img.UnlockFocus();
             */

            var    imageData = img.AsTiff();
            var    imageRep  = NSBitmapImageRep.ImageRepsWithData(imageData)[0] as NSBitmapImageRep;
            var    jpegData  = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, null);
            byte[] jpeg      = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);
            return(jpeg);
#elif __IOS__
            UIImage uiimage = new UIImage(fileName);

            UIGraphics.BeginImageContextWithOptions(uiimage.Size, false, 0);
            var context = UIGraphics.GetCurrentContext();

            uiimage.Draw(new CGPoint());
            context.SetStrokeColor(UIColor.Red.CGColor);
            context.SetLineWidth(2);
            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects = ScaleLocation(
                    annotations[i].Rectangle,
                    (int)uiimage.Size.Width,
                    (int)uiimage.Size.Height);
                CGRect cgRect = new CGRect(
                    (nfloat)rects[0],
                    (nfloat)rects[1],
                    (nfloat)(rects[2] - rects[0]),
                    (nfloat)(rects[3] - rects[1]));
                context.AddRect(cgRect);
                context.DrawPath(CGPathDrawingMode.Stroke);
            }
            UIImage imgWithRect = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            var    jpegData = imgWithRect.AsJPEG();
            byte[] jpeg     = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);
            return(jpeg);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                Bitmap img = new Bitmap(fileName);

                if (annotations != null)
                {
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        for (int i = 0; i < annotations.Length; i++)
                        {
                            if (annotations[i].Rectangle != null)
                            {
                                float[]    rects  = ScaleLocation(annotations[i].Rectangle, img.Width, img.Height);
                                PointF     origin = new PointF(rects[0], rects[1]);
                                RectangleF rect   = new RectangleF(rects[0], rects[1], rects[2] - rects[0], rects[3] - rects[1]);
                                Pen        redPen = new Pen(Color.Red, 3);
                                g.DrawRectangle(redPen, Rectangle.Round(rect));

                                String label = annotations[i].Label;
                                if (label != null)
                                {
                                    g.DrawString(label, new Font(FontFamily.GenericSansSerif, 20f), Brushes.Red, origin);
                                }
                            }
                        }
                        g.Save();
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return(ms.ToArray());
                }
            }
            else
            {
                throw new Exception("DrawResultsToJpeg Not implemented for this platform");
            }
#endif
        }
 void Initialise()
 {
     mTestPaint = new Paint();
     mTestPaint.Set(this.Paint);
     //max size defaults to the initially specified text size unless it is too small
 }
Beispiel #56
0
        void DrawShadow(Canvas canvas)
        {
            if (_shadowCanvas == null)
            {
                _shadowCanvas = new Canvas();
            }

            if (_shadowPaint == null)
            {
                _shadowPaint = new Android.Graphics.Paint
                {
                    AntiAlias    = true,
                    Dither       = true,
                    FilterBitmap = true
                }
            }
            ;

            Graphics.Color solidColor = null;

            // If need to redraw shadow
            if (_invalidateShadow)
            {
                var viewHeight = _viewBounds.Height();
                var viewWidth  = _viewBounds.Width();

                if (GetChildAt(0) is AView child)
                {
                    if (viewHeight == 0)
                    {
                        viewHeight = child.MeasuredHeight;
                    }

                    if (viewWidth == 0)
                    {
                        viewWidth = child.MeasuredWidth;
                    }
                }

                // If bounds is zero
                if (viewHeight != 0 && viewWidth != 0)
                {
                    var bitmapHeight = viewHeight + MaximumRadius;
                    var bitmapWidth  = viewWidth + MaximumRadius;

                    // Reset bitmap to bounds
                    _shadowBitmap = Bitmap.CreateBitmap(
                        bitmapWidth, bitmapHeight, Bitmap.Config.Argb8888
                        );

                    // Reset Canvas
                    _shadowCanvas.SetBitmap(_shadowBitmap);

                    _invalidateShadow = false;

                    // Create the local copy of all content to draw bitmap as a
                    // bottom layer of natural canvas.
                    base.DispatchDraw(_shadowCanvas);

                    // Get the alpha bounds of bitmap
                    Bitmap extractAlpha = _shadowBitmap.ExtractAlpha();

                    // Clear past content content to draw shadow
                    _shadowCanvas.DrawColor(Android.Graphics.Color.Black, PorterDuff.Mode.Clear);

                    var shadowOpacity = (float)Shadow.Opacity;

                    if (Shadow.Paint is LinearGradientPaint linearGradientPaint)
                    {
                        var linearGradientShaderFactory = PaintExtensions.GetLinearGradientShaderFactory(linearGradientPaint, shadowOpacity);
                        _shadowPaint.SetShader(linearGradientShaderFactory.Resize(bitmapWidth, bitmapHeight));
                    }
                    if (Shadow.Paint is RadialGradientPaint radialGradientPaint)
                    {
                        var radialGradientShaderFactory = PaintExtensions.GetRadialGradientShaderFactory(radialGradientPaint, shadowOpacity);
                        _shadowPaint.SetShader(radialGradientShaderFactory.Resize(bitmapWidth, bitmapHeight));
                    }
                    if (Shadow.Paint is SolidPaint solidPaint)
                    {
                        solidColor = solidPaint.ToColor();
#pragma warning disable CA1416 // https://github.com/xamarin/xamarin-android/issues/6962
                        _shadowPaint.Color = solidColor.WithAlpha(shadowOpacity).ToPlatform();
#pragma warning restore CA1416
                    }

                    // Apply the shadow radius
                    var radius = Shadow.Radius;

                    if (radius <= 0)
                    {
                        radius = 0.01f;
                    }

                    if (radius > 100)
                    {
                        radius = MaximumRadius;
                    }

                    _shadowPaint.SetMaskFilter(new BlurMaskFilter(radius, BlurMaskFilter.Blur.Normal));

                    float shadowOffsetX = (float)Shadow.Offset.X;
                    float shadowOffsetY = (float)Shadow.Offset.Y;

                    if (Clip == null)
                    {
                        _shadowCanvas.DrawBitmap(extractAlpha, shadowOffsetX, shadowOffsetY, _shadowPaint);
                    }
                    else
                    {
                        var bounds = new Graphics.RectF(0, 0, canvas.Width, canvas.Height);
                        var path   = Clip.PathForBounds(bounds)?.AsAndroidPath();

                        path.Offset(shadowOffsetX, shadowOffsetY);

                        _shadowCanvas.DrawPath(path, _shadowPaint);
                    }

                    // Recycle and clear extracted alpha
                    extractAlpha.Recycle();
                }
                else
                {
                    // Create placeholder bitmap when size is zero and wait until new size coming up
                    _shadowBitmap = Bitmap.CreateBitmap(1, 1, Bitmap.Config.Rgb565 !);
                }
            }

            // Reset alpha to draw child with full alpha
            if (solidColor != null)
#pragma warning disable CA1416 // https://github.com/xamarin/xamarin-android/issues/6962
            {
                _shadowPaint.Color = solidColor.ToPlatform();
            }
#pragma warning restore CA1416

            // Draw shadow bitmap
            if (_shadowCanvas != null && _shadowBitmap != null && !_shadowBitmap.IsRecycled)
            {
                canvas.DrawBitmap(_shadowBitmap, 0.0F, 0.0F, _shadowPaint);
            }
        }

        void ClearShadowResources()
        {
            _shadowCanvas?.Dispose();
            _shadowPaint?.Dispose();
            _shadowBitmap?.Dispose();
            _shadowCanvas = null;
            _shadowPaint  = null;
            _shadowBitmap = null;
        }
    }
Beispiel #57
0
 public DrawLine(Context context) : base(context)
 {
     paint = new Android.Graphics.Paint();
 }
 /// <summary>
 /// set default values of Paint
 /// </summary>
 /// <param name="value">Value.</param>
 public static AG.Paint DefaultSettings(this AG.Paint value)
 {
     value.AntiAlias    = true;
     value.FilterBitmap = true;
     return(value);
 }
Beispiel #59
0
 public void SetPaint(AG.Paint dest)
 {
     dest.SetFont(this.Font);
     dest.TextAlign = AG.Paint.Align.Left;
 }