예제 #1
1
		void Initialize ()
		{
			mPaint = new Paint ();
			mPaint.Color = Color.Black;
			mPaint.AntiAlias = true;
			mPaint.SetStyle (Paint.Style.Fill);
		}
예제 #2
1
      // assumptions for pixel snapping: 
      // - the drawing context itself is pixel snapped
      // - all strokes have same thickness
      // - the thickness is a whole number


      #region ELLIPSES
      /// <summary>See <c>WpfExtensions</c> for details.</summary>
      public static void DrawEllipse(DrawingContext dc, Paint paint, Point center, double radiusX, double radiusY, bool snapToPixel) {
         // get brush and stroke resources
         if (paint == null) return;
         var fill = paint.Fill;
         var hasFill = (fill != null);
         var strokes = paint.GetStrokePens().ToArray();
         var numStrokes = strokes.Length;
         if (!hasFill && numStrokes == 0) return;

         var halfThickness = Math.Round(numStrokes > 0? strokes[0].Thickness : 0.0) / 2;
         if (snapToPixel) {
            center = new Point(center.X + halfThickness, center.Y + halfThickness);
         }

         if (numStrokes > 0) {
            for (var i = 0; i < numStrokes - 1; i++) {
               dc.DrawEllipse(null, strokes[i], center, radiusX, radiusY);
               radiusX = (radiusX - 2 * halfThickness).Max(0);
               radiusY = (radiusY - 2 * halfThickness).Max(0);
            }
            dc.DrawEllipse(fill, strokes[numStrokes - 1], center, radiusX, radiusY);
         } else {
            dc.DrawEllipse(fill, null, center, radiusX, radiusY);
         }

      }
		public CircleImageView(Context context, IAttributeSet attrs, int defStyle)
			: base(context, attrs, defStyle)
		{

			// init paint
			paint = new Paint();
			paint.AntiAlias = true;

			paintBorder = new Paint();
			paintBorder.AntiAlias = true;

			// load the styled attributes and set their properties
			TypedArray attributes = context.ObtainStyledAttributes(attrs, Resource.Styleable.CircularImageView, defStyle, 0);

			if (attributes.GetBoolean(Resource.Styleable.CircularImageView_border, true))
			{
				int defaultBorderSize = (int)(4 * context.Resources.DisplayMetrics.Density+ 0.5f);
				BorderWidth = attributes.GetDimensionPixelOffset(Resource.Styleable.CircularImageView_border_width, defaultBorderSize);
				BorderColor = attributes.GetColor(Resource.Styleable.CircularImageView_border_color, Color.White);
			}

			if (attributes.GetBoolean(Resource.Styleable.CircularImageView_shadow, false))
			{
				addShadow();
			}
		}
        static Bitmap GetCroppedBitmap (Bitmap bmp, int radius)
        {
            Bitmap sbmp;
            if (bmp.Width != radius || bmp.Height != radius)
                sbmp = Bitmap.CreateScaledBitmap (bmp, radius, radius, false);
            else
                sbmp = bmp;
            var output = Bitmap.CreateBitmap (sbmp.Width,
                             sbmp.Height, Bitmap.Config.Argb8888);
            var canvas = new Canvas (output);

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

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

            return output;
        }
예제 #5
0
		void Initialize ()
		{
			_basePaint = new Paint ();
			_basePaint.Color = Color.Black;
			_basePaint.AntiAlias = true;
			_basePaint.SetStyle (Paint.Style.Fill);

			_gridPaint = new Paint ();
			_gridPaint.SetStyle (Paint.Style.Stroke);
			_gridPaint.Color = Color.ParseColor (RSColors.RS_LIGHT_GRAY);

			_circlesPaint = new Paint ();
			_circlesPaint.Color = Color.ParseColor (RSColors.PURPLE_4);
			_circlesPaint.SetStyle (Paint.Style.Fill);
			_circlesPaint.AntiAlias = true;

			_dataLabelPaint = new Paint ();
			_dataLabelPaint.Color = Color.ParseColor (RSColors.GREEN_4);
			_dataLabelPaint.TextSize = PixelUtil.GetPixelFromDP (dataLabelSize, _context.Resources);
			_dataLabelPaint.SetStyle (Paint.Style.Stroke);
			_dataLabelPaint.AntiAlias = true;
			_dataLabelPaint.SetTypeface (Typeface.DefaultBold);
			_dataLabelPaint.TextAlign = Paint.Align.Center;

			_dataLabelBgPaint = new Paint ();
			_dataLabelBgPaint.Color = Color.White;
			_dataLabelBgPaint.SetStyle (Paint.Style.Fill);

			_xLabelPaint = new Paint ();
			_xLabelPaint.Color = Color.Black;
			_xLabelPaint.SetStyle (Paint.Style.Stroke);
			_xLabelPaint.AntiAlias = true;
			_xLabelPaint.TextAlign = Paint.Align.Center;
			_xLabelPaint.TextSize = PixelUtil.GetPixelFromDP (xLabelSize, _context.Resources);
		}
예제 #6
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);

            SetContentView(Resource.Layout.Main);

            _colorMatrix = new ColorMatrix();
            _colorMatrixFilter = new ColorMatrixColorFilter(_colorMatrix);

            _paint = new Paint();
            _paint.SetColorFilter(_colorMatrixFilter);

            var contrast = FindViewById<SeekBar>(Resource.Id.contrast);
            contrast.KeyProgressIncrement = 1;
            contrast.ProgressChanged += ContrastChanged;

            var brightness = FindViewById<SeekBar>(Resource.Id.brightness);
            brightness.KeyProgressIncrement = 1;
            brightness.ProgressChanged += BrightnessChanged;

            var saturation = FindViewById<SeekBar>(Resource.Id.saturation);
            saturation.KeyProgressIncrement = 1;
            saturation.ProgressChanged += SaturationChanged;

            var imageSelector = FindViewById<Button>(Resource.Id.selectImage);
            imageSelector.Click += ImagesSelectorClick;

            _imageViewer = FindViewById<ImageView>(Resource.Id.imageViewer);
        }
예제 #7
0
 protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime)
 {
     try
     {
         var radius = Math.Min(Width, Height) / 2;
         var strokeWidth = 10;
         radius -= strokeWidth / 2;
         //Create path to clip
         var path = new Path();
         path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
         canvas.Save();
         canvas.ClipPath(path);
         var result = base.DrawChild(canvas, child, drawingTime);
         canvas.Restore();
         // 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 = global::Android.Graphics.Color.White;
         canvas.DrawPath(path, paint);
         //Properly dispose
         paint.Dispose();
         path.Dispose();
         return result;
     }
     catch (Exception ex)
     {
         Console.WriteLine("Unable to create circle image: " + ex);
     }
     return base.DrawChild(canvas, child, drawingTime);
 }
예제 #8
0
        void OnElementSizeChanged(object sender, EventArgs e)
        {
            var elem = sender as View;
            if (elem == null)
                return;

            var density = Resources.System.DisplayMetrics.Density;

            using (var imageBitmap = Bitmap.CreateBitmap((int)((elem.Width + 2) * density), (int)((elem.Height + 1) * density), Bitmap.Config.Argb8888))
            using (var canvas = new Canvas(imageBitmap))
            using (var paint = new Paint() { Dither = false, Color = Xamarin.Forms.Color.White.ToAndroid(), AntiAlias = true })
            {
                paint.Hinting = PaintHinting.On;
                paint.Flags = PaintFlags.AntiAlias;
                paint.SetStyle(Paint.Style.Stroke);
                paint.StrokeWidth = 2 * density;

                var height = (float)elem.Height;

                canvas.DrawRoundRect(new RectF(density, density, (float)(elem.Width) * density, (float)(height) * density), height * density / 2, height * density / 2, paint);
                canvas.Density = (int)density;

                Container.Background = new BitmapDrawable(imageBitmap);
            }
        }
예제 #9
0
		// If you would like to create a circle of the image set pixels to half the width of the image.
		internal static   Bitmap GetRoundedCornerBitmap(Bitmap bitmap, int pixels)
		{
			Bitmap output = null;

			try
			{
				output = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, Bitmap.Config.Argb8888);
				Canvas canvas = new Canvas(output);

				Color color = new Color(66, 66, 66);
				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, bitmap.Width, bitmap.Height);
				RectF rectF = new RectF(rect);
				float roundPx = pixels;

				paint.AntiAlias = true;
				canvas.DrawARGB(0, 0, 0, 0);
				paint.Color = color;
				canvas.DrawRoundRect(rectF, roundPx, roundPx, paint);

				paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
				canvas.DrawBitmap(bitmap, rect, rect, paint);
			}
			catch (System.Exception err)
			{
				System.Console.WriteLine ("GetRoundedCornerBitmap Error - " + err.Message);
			}

			return output;
		}
	    public BezelImageView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
		{
			// Attribute initialization
	        var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.BezelImageView, defStyle, 0);
	
	        mMaskDrawable = a.GetDrawable(Resource.Styleable.BezelImageView_maskDrawable);
	        if (mMaskDrawable == null) {
	            mMaskDrawable = Resources.GetDrawable(Resource.Drawable.bezel_mask);
	        }
	        mMaskDrawable.Callback = this;
	
	        mBorderDrawable = a.GetDrawable(Resource.Styleable.BezelImageView_borderDrawable);
	        if (mBorderDrawable == null) {
	            mBorderDrawable = Resources.GetDrawable(Resource.Drawable.bezel_border);
	        }
	        mBorderDrawable.Callback = this;
	
	        a.Recycle();
	
	        // Other initialization
	        mMaskedPaint = new Paint();
	        mMaskedPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcAtop));
	
	        mCopyPaint = new Paint();
		}
예제 #11
0
        public override void Draw(Android.Graphics.Canvas canvas)
        {
            base.Draw (canvas);

            Paint mBgPaints = new Paint ();
            mBgPaints.AntiAlias = true;
            mBgPaints.SetStyle (Paint.Style.Fill);
            mBgPaints.Color = Color.Blue;
            mBgPaints.StrokeWidth = 0.5f;

            Paint tPaint = new Paint ();
            tPaint.Alpha = 0;
            canvas.DrawColor (tPaint.Color);

            RectF mOvals = new RectF (40, 40, layout.MeasuredWidth - 40, layout.MeasuredHeight - 40);

            decimal total = 0;
            foreach (SecuritiesViewModel.PieChartValue value in securitiesViewModel.DataForPieChart ()) {
                total += value.amount;
            }

            if (total == 0) {
                return;
            }

            decimal degressPerAmount = 360 / total;
            decimal currentAngle = 0;
            foreach (SecuritiesViewModel.PieChartValue value in securitiesViewModel.DataForPieChart ()) {
                canvas.DrawArc (mOvals, (float)currentAngle, (float)(degressPerAmount * value.amount), true, mBgPaints);
                currentAngle += (degressPerAmount * value.amount);
                mBgPaints.SetARGB (255, new Random ().Next (256), new Random ().Next (256), new Random ().Next (256));
            }
        }
예제 #12
0
			public SampleView (Context context) : base (context)
			{
				Focusable = true;

				mPaint = new Paint ();
				mPaint.AntiAlias = true;
			}
예제 #13
0
파일: SVGFilter.cs 프로젝트: jdluzen/xamsvg
		public void applyFilterElements(Paint pPaint) {
			this.mSVGAttributes.getFloatAttribute(SVGConstants.ATTRIBUTE_X, true);
			List<ISVGFilterElement> svgFilterElements = this.mSVGFilterElements;
			for(int i = 0; i < svgFilterElements.Count; i++) {
				svgFilterElements[i].Apply(pPaint);
			}
		}
예제 #14
0
		static void test_alphagradients (Canvas canvas)
		{
			canvas.translate (20, 10);

			RectF r = new RectF (10, 10, 410, 30);
			Paint p = new Paint (), p2 = new Paint ();
			p2.setStyle (Paint.Style.STROKE);

			using (Shader shader = setgrad (r, 0xFF00FF00, 0x0000FF00))
				p.setShader (shader);
			canvas.drawRect (r, p);
			canvas.drawRect (r, p2);

			r.offset (0, r.height () + 4);
			using (Shader shader = setgrad(r, 0xFF00FF00, 0x00000000))
				p.setShader (shader);
			canvas.drawRect (r, p);
			canvas.drawRect (r, p2);

			r.offset (0, r.height () + 4);
			using (Shader shader = setgrad(r, 0xFF00FF00, 0x00FF0000))
				p.setShader (shader);
			canvas.drawRect (r, p);
			canvas.drawRect (r, p2);
		}
        private static void ApplyCustomTypeFace(Paint paint, Typeface tf, Android.Graphics.Color color)
        {
            int oldStyle;
            Typeface old = paint.Typeface;
            if (old == null)
            {
                oldStyle = 0;
            }
            else
            {
                oldStyle = (int)old.Style;
            }

            int fake = oldStyle & ~(int)tf.Style;
            if ((fake & (int)TypefaceStyle.Bold) != 0)
            {
                paint.FakeBoldText = true;
            }

            if ((fake & (int)TypefaceStyle.Italic) != 0)
            {
                paint.TextSkewX = -0.25f;
            }



            paint.SetARGB(color.A, color.R, color.G, color.B);

            paint.SetTypeface(tf);
        }
		public SlidingTabStrip(Context context, IAttributeSet Attrs):base(context, Attrs) {
			SetWillNotDraw(false);

			float density = Resources.DisplayMetrics.Density;

			TypedValue outValue = new TypedValue();
			context.Theme.ResolveAttribute(Android.Resource.Attribute.ColorForeground, outValue, true);
			int themeForegroundColor =  outValue.Data;

			_defaultBottomBorderColor = SetColorAlpha(themeForegroundColor,0x26);

			_defaultTabColorizer = new SimpleTabColorizer();
			_defaultTabColorizer.SetIndicatorColors(0xFF33B5);
			_defaultTabColorizer.SetDividerColors(SetColorAlpha(themeForegroundColor,0x20));

			_bottomBorderThickness = (int) (2 * density);
			_bottomBorderPaint = new Paint();
			_bottomBorderPaint.Color = Color.White;

			_selectedIndicatorThickness = (int) (6 * density);
			_selectedIndicatorPaint = new Paint();

			_dividerHeight = 0.5f;
			_dividerPaint = new Paint();
			_dividerPaint.StrokeWidth=((int) (1 * density));
		}
예제 #17
0
        public override bool OnTouchEvent(MotionEvent e)
        {
            _Paint = new Paint ();
            _Paint.Color = new Android.Graphics.Color (255, 0, 0);
            _Paint.StrokeWidth = 20;
            _Paint.StrokeCap = Paint.Cap.Round;
            var imageView = FindViewById<ImageView> (Resource.Id.myImageView);
            Bitmap immutableBitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri);
            _Bmp = immutableBitmap.Copy(Bitmap.Config.Argb8888, true);
            _Canvas = new Canvas(_Bmp);
            imageView.SetImageBitmap (_Bmp);
                switch (e.Action)
                {

                default:
                {
                    _StartPt.X=e.RawX;
                    _StartPt.Y=e.RawY;
                    Console.WriteLine ("inside default:{0}","default");
                    DrawPoint (_Canvas);
                    break;
                }
                }

            return true;
        }
예제 #18
0
        public AvatarProgressRelativeLayout(Context context,int width,int progresswidth,int stokewidth,float percent)
            : base(context)
        {
            nn_context = context;
            nn_paint = new Paint ();
            nn_paint.AntiAlias = true;
            nn_outcolor = context.Resources.GetColor (Resource.Color.soarnix_bg_gray);
            nn_progressremainingcolor = Color.WhiteSmoke;
            nn_innercontainercolor = Color.White;
            nn_progresscolor = context.Resources.GetColor (Resource.Color.iosblue);
            nn_radius = TapUtil.dptodx(width)/2;

            this.stokewidthdp = stokewidth;
            this.progresswidthdp = progresswidth;

            progresssendangle =360 * percent;

            RelativeLayout.LayoutParams layoutparam=new RelativeLayout.LayoutParams (nn_radius*2,nn_radius*2);
            layoutparam.AddRule (LayoutRules.CenterInParent);
            this.LayoutParameters = layoutparam;

            SetLayerType (LayerType.Software,null);

            SetWillNotDraw(false);
        }
		public static Bitmap ToRounded(Bitmap source, float rad, double cropWidthRatio, double cropHeightRatio, double borderSize, string borderHexColor)
		{
			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);

			float cropX = (float)((sourceWidth - desiredWidth) / 2d);
			float cropY = (float)((sourceHeight - desiredHeight) / 2d);

			if (rad == 0)
				rad = (float)(Math.Min(desiredWidth, desiredHeight) / 2d);
			else
				rad = (float)(rad * (desiredWidth + desiredHeight) / 2d / 500d);

			Bitmap bitmap = Bitmap.CreateBitmap((int)desiredWidth, (int)desiredHeight, Bitmap.Config.Argb8888);

			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 = true;

				RectF rectF = new RectF(0f, 0f, (float)desiredWidth, (float)desiredHeight);
				canvas.DrawRoundRect(rectF, rad, rad, paint);

				if (borderSize > 0d) 
				{
					borderSize = (borderSize * (desiredWidth + desiredHeight) / 2d / 500d);
					paint.Color = borderHexColor.ToColor(); ;
					paint.SetStyle(Paint.Style.Stroke);
					paint.StrokeWidth = (float)borderSize;
					paint.SetShader(null);

					RectF borderRectF = new RectF((float)(0d + borderSize/2d), (float)(0d + borderSize/2d), 
						(float)(desiredWidth - borderSize/2d), (float)(desiredHeight - borderSize/2d));

					canvas.DrawRoundRect(borderRectF, rad, rad, paint);
				}

				return bitmap;				
			}
		}
예제 #20
0
        public SlidingTabStrip1(Context context, IAttributeSet attrs)
            : base(context, attrs)
        {
            SetWillNotDraw(false);

            float density = Resources.DisplayMetrics.Density;

            TypedValue outValue = new TypedValue();
            context.Theme.ResolveAttribute(Android.Resource.Attribute.ColorForeground, outValue, true);
            int themeForeGround = outValue.Data;
            mDefaultBottomBorderColor = SetColorAlpha(themeForeGround, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

            mDefaultTabColorizer = new SimpleTabColorizer1();
            mDefaultTabColorizer.IndicatorColors = INDICATOR_COLORS;
            mDefaultTabColorizer.DividerColors = DIVIDER_COLORS;

            mBottomBorderThickness = (int)(DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
            mBottomBorderPaint = new Paint();
            mBottomBorderPaint.Color = GetColorFromInteger(0xC5C5C5); //Gray

            mSelectedIndicatorThickness = (int)(SELECTED_INDICATOR_THICKNESS_DIPS * density);
            mSelectedIndicatorPaint = new Paint();

            mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
            mDividerPaint = new Paint();
            mDividerPaint.StrokeWidth = (int)(DEFAULT_DIVIDER_THICKNESS_DIPS * density);
        }
        public Bitmap GetBitmapMarker(Context mContext, int resourceId, string text)
        {
            Resources resources = mContext.Resources;
            float scale = resources.DisplayMetrics.Density;
            Bitmap bitmap = BitmapFactory.DecodeResource(resources, resourceId);

            Bitmap.Config bitmapConfig = bitmap.GetConfig();

            // set default bitmap config if none
            if (bitmapConfig == null)
                bitmapConfig = Bitmap.Config.Argb8888;

            bitmap = bitmap.Copy(bitmapConfig, true);

            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(PaintFlags.AntiAlias);
            paint.Color = global::Android.Graphics.Color.Black;
            paint.TextSize = ((int)(14 * scale));
            paint.SetShadowLayer(1f, 0f, 1f, global::Android.Graphics.Color.White);

            // draw text to the Canvas center
            Rect bounds = new Rect();
            paint.GetTextBounds(text, 0, text.Length, bounds);
            int x = (bitmap.Width - bounds.Width()) / 2;
            int y = (bitmap.Height + bounds.Height()) / 2 - 20;

            canvas.DrawText(text, x, y, paint);

            return bitmap;
        }
예제 #22
0
파일: ShapeView.cs 프로젝트: rfcclub/dot42
 protected void DrawShape(Canvas canvas)
 {
   Paint paint = new Paint();
   paint.Color = Color;
   switch (Shape)
   {
     case ShapeEnum.RectangleShape:
       canvas.DrawRect(0, 0, ShapeWidth, ShapeHeight, paint);
       break;
     case ShapeEnum.OvalShape:
       canvas.DrawOval(new RectF(0, 0, ShapeWidth, ShapeHeight), paint);
       break;
     case ShapeEnum.TriangleShape:
         Path path = new Path();
         path.MoveTo(ShapeWidth / 2, 0);
         path.LineTo(ShapeWidth, ShapeHeight);
         path.LineTo(0,ShapeHeight);
         path.Close();
       canvas.DrawPath(path, paint);
       break;
     default:
       canvas.DrawCircle(ShapeWidth / 2, ShapeHeight / 2, ShapeWidth / 2, paint); 
       break;
   }
 }
        public Bitmap Transform(Bitmap source)
        {
            int size = Math.Min(source.Width, source.Height);

            int width = (source.Width - size) / 2;
            int height = (source.Height - size) / 2;

            var bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb4444);

            var canvas = new Canvas(bitmap);
            var paint = new Paint();
            var shader =
                new BitmapShader(source, BitmapShader.TileMode.Clamp, BitmapShader.TileMode.Clamp);
            if (width != 0 || height != 0)
            {
                // source isn't square, move viewport to center
                var matrix = new Matrix();
                matrix.SetTranslate(-width, -height);
                shader.SetLocalMatrix(matrix);
            }
            paint.SetShader(shader);
            paint.AntiAlias = true;

            float r = size / 2f;
            canvas.DrawCircle(r, r, r, paint);

            source.Recycle();

            return bitmap;
        }
예제 #24
0
	public DrawingImageView(Context context, Fragment fragment): base(context) {
		mPaint = new Paint();
		mPaint.AntiAlias = true;
		mPaint.Dither = true;
		mPaint.Color = Color.Yellow;
		mPaint.SetStyle (Paint.Style.Stroke);
		mPaint.StrokeJoin = Paint.Join.Round;
		mPaint.StrokeCap = Paint.Cap.Round;
		mPaint.StrokeWidth = 10;

		cPaint = new Paint ();
		cPaint.Color = Color.Yellow;
		cPaint.StrokeJoin = Paint.Join.Round;
		cPaint.StrokeCap = Paint.Cap.Round;
		cPaint.SetTypeface(Typeface.Default);
		cPaint.TextSize = 40;

		mPath = new Android.Graphics.Path();
		mBitmapPaint = new Paint();
		mBitmapPaint.Color = Color.Yellow;

		DrawingStatus = DrawingType.None;

		_fragment = fragment;
	}
예제 #25
0
파일: Spiral.cs 프로젝트: hakeemsm/XobotOS
		protected override void onDraw (Canvas canvas)
		{
			canvas.drawColor (unchecked((int)0xFFDDDDDD));

			Paint paint = new Paint ();
			paint.setAntiAlias (true);
			paint.setStyle (Paint.Style.STROKE);
			paint.setStrokeWidth (3);
			paint.setStyle (Paint.Style.FILL);

			RectF r = new RectF ();
			float t, x, y;

			t = GetAnimScalar (25, 500);

			canvas.translate (320, 240);

			for (int i = 0; i < 35; i++) {
				paint.setColor (unchecked((int)0xFFF00FF0 - i * 0x04000000));
				double step = Math.PI / (55 - i);
				double angle = t * step;
				x = (20 + i * 5) * (float)Math.Sin (angle);
				y = (20 + i * 5) * (float)Math.Cos (angle);
				r.set (x, y, x + 10, y + 10);
				canvas.drawRect (r, paint);
			}
		}
예제 #26
0
        //        Tile tile;
        public MapPlotter(int size)
        {
            this.size = size;

            defaultPaint = new Paint();
            defaultPaint.Fill = PlotterHelper.DEFAULT_COLOR;

            roadPaint = new Paint();
            roadPaint.StrokeCap = PenLineCap.Round;

            roadBorderPaint = new Paint();
            roadBorderPaint.Stroke = PlotterHelper.ROAD_BORDER_COLOR;
            roadBorderPaint.StrokeCap = PenLineCap.Round;

            grassPaint = new Paint();
            grassPaint.Fill = PlotterHelper.NATURE_GRASS_COLOR;

            waterPaint = new Paint();
            waterPaint.Fill = PlotterHelper.NATURE_WATER_COLOR;

            riverPaint = new Paint();
            riverPaint.Stroke = PlotterHelper.NATURE_RIVER_COLOR;
            riverPaint.StrokeCap = PenLineCap.Round;

            buildingPaint = new Paint();
        }
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw (canvas);

            var r = new Rect ();
            this.GetLocalVisibleRect (r);

            var half = r.Width() / 2;
            var height = r.Height();

            var percentage = (this.Limit - Math.Abs(this.CurrentValue)) / this.Limit;


            var paint = new Paint()
            {
                Color = this.CurrentValue < 0 ? this.negativeColor : this.positiveColor,
                StrokeWidth = 5
            };

            paint.SetStyle(Paint.Style.Fill);

            if (this.CurrentValue < 0)
            {
                var start = (float)percentage * half;
                var size = half - start;
                canvas.DrawRect (new Rect ((int)start, 0, (int)(start + size), height), paint);
            }
            else
            {
                canvas.DrawRect (new Rect((int)half, 0, (int)(half + percentage * half), height), paint);
            }
        }
			public override Android.Graphics.Drawables.Drawable GetBackgroundForPage (int row, int column)
			{
				Point pt = new Point (column, row);
				Drawable drawable;
				if (!mBackgrounds.ContainsKey(pt))
				{
					// the key wasn't found in Dictionary
					var bm = Bitmap.CreateBitmap(200, 200, Bitmap.Config.Argb8888);
					var c = new Canvas(bm);
					var p = new Paint();
					// Clear previous image.
					c.DrawRect(0, 0, 200, 200, p);
					p.AntiAlias = true;
					p.SetTypeface(Typeface.Default);
					p.TextSize = 64;
					p.Color = Color.LightGray;
					p.TextAlign = Paint.Align.Center;
					c.DrawText(column + "-" + row, 100, 100, p);
					drawable = new BitmapDrawable(owner.Resources, bm);
					mBackgrounds.Add(pt, drawable);
				}
				else
				{
					// the key was found
					drawable = mBackgrounds[pt];
				}
				return drawable;
			}
예제 #29
0
 public new void Draw(Canvas canvas, Paint paint)
 {
     int viewWidth = mProgressBar.Width;
     int viewHeight = mProgressBar.Height;
     canvas.DrawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius), mShadowPaint);
     canvas.DrawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
 }
        public override void Draw(Android.Graphics.Canvas canvas)
        {
            base.Draw(canvas);

            var rect = new RectF(0,0,300,300);
            switch (TheShape)
            {
                case Shape.Circle:
                    canvas.DrawOval(rect, new Paint() { Color = Color.Aqua });
                    break;
                case Shape.Square:
                    canvas.DrawRect(rect, new Paint() { Color = Color.Red });
                    break;
                case Shape.Triangle:
                    var path = new Path();
                    path.MoveTo(rect.CenterX(), 0);
                    path.LineTo(0, rect.Height());
                    path.LineTo(rect.Width(), rect.Height());
                    path.Close();

                    var paint = new Paint() {Color = Color.Magenta};
                    paint.SetStyle(Paint.Style.Fill);
                    canvas.DrawPath(path, paint);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
예제 #31
0
        void saveLayer()
        {
            var pictureRecorder = new PictureRecorder();
            var canvas          = new RecorderCanvas(pictureRecorder);
            var paint1          = new Paint {
                color = new Color(0xFFFFFFFF),
            };

            var path1 = new Path();

            path1.moveTo(0, 0);
            path1.lineTo(0, 90);
            path1.lineTo(90, 90);
            path1.lineTo(90, 0);
            path1.close();
            canvas.drawPath(path1, paint1);


            var paint = new Paint {
                color = new Color(0xFFFF0000),
            };

            var path = new Path();

            path.moveTo(20, 20);
            path.lineTo(20, 70);
            path.lineTo(70, 70);
            path.lineTo(70, 20);
            path.close();

            canvas.drawPath(path, paint);

            var paint2 = new Paint {
                color = new Color(0xFFFFFF00),
            };

            var path2 = new Path();

            path2.moveTo(30, 30);
            path2.lineTo(30, 60);
            path2.lineTo(60, 60);
            path2.lineTo(60, 30);
            path2.close();

            canvas.drawPath(path2, paint2);

            var picture = pictureRecorder.endRecording();

            var editorCanvas = new CommandBufferCanvas(this._renderTexture, Window.instance.devicePixelRatio,
                                                       this._meshPool);

            editorCanvas.saveLayer(
                picture.paintBounds, new Paint {
                color = new Color(0xFFFFFFFF),
            });
            editorCanvas.drawPicture(picture);
            editorCanvas.restore();

            editorCanvas.saveLayer(Unity.UIWidgets.ui.Rect.fromLTWH(45, 45, 90, 90), new Paint {
                color    = new Color(0xFFFFFFFF),
                backdrop = ImageFilter.blur(3f, 3f)
            });
            editorCanvas.restore();

            editorCanvas.flush();
        }
예제 #32
0
        void drawLine()
        {
            var canvas = new CommandBufferCanvas(this._renderTexture, Window.instance.devicePixelRatio,
                                                 this._meshPool);

            var paint = new Paint {
                color       = new Color(0xFFFF0000),
                style       = PaintingStyle.stroke,
                strokeWidth = 10,
                shader      = Gradient.linear(new Offset(10, 10), new Offset(180, 180), new List <Color>()
                {
                    Colors.red, Colors.green, Colors.yellow
                }, null, TileMode.clamp)
            };

            canvas.drawLine(
                new Offset(10, 20),
                new Offset(50, 20),
                paint);

            canvas.drawLine(
                new Offset(10, 10),
                new Offset(100, 100),
                paint);

            canvas.drawLine(
                new Offset(10, 10),
                new Offset(10, 50),
                paint);

            canvas.drawLine(
                new Offset(40, 10),
                new Offset(90, 10),
                paint);


            canvas.drawArc(Unity.UIWidgets.ui.Rect.fromLTWH(200, 200, 100, 100), Mathf.PI / 4,
                           -Mathf.PI / 2 + Mathf.PI * 4 - 1, true, paint);

            paint.maskFilter  = MaskFilter.blur(BlurStyle.normal, 1);
            paint.strokeWidth = 4;

            canvas.drawLine(
                new Offset(40, 20),
                new Offset(120, 190),
                paint);

            canvas.scale(3);
            TextBlob textBlob = new TextBlob("This is a text blob", 0, 19, new Vector2d[] {
                new Vector2d(10, 0),
                new Vector2d(20, 0),
                new Vector2d(30, 0),
                new Vector2d(40, 0),
                new Vector2d(50, 0),
                new Vector2d(60, 0),
                new Vector2d(70, 0),
                new Vector2d(80, 0),
                new Vector2d(90, 0),
                new Vector2d(100, 0),
                new Vector2d(110, 0),
                new Vector2d(120, 0),
                new Vector2d(130, 0),
                new Vector2d(140, 0),
                new Vector2d(150, 0),
                new Vector2d(160, 0),
                new Vector2d(170, 0),
                new Vector2d(180, 0),
                new Vector2d(190, 0),
            }, Unity.UIWidgets.ui.Rect.fromLTWH(0, 0, 200, 50), new TextStyle());

            canvas.drawTextBlob(textBlob, new Offset(100, 100), paint);

            canvas.drawLine(
                new Offset(10, 30),
                new Offset(10, 60),
                new Paint()
            {
                style = PaintingStyle.stroke, strokeWidth = 0.1f
            });

            canvas.drawLine(
                new Offset(20, 30),
                new Offset(20, 60),
                new Paint()
            {
                style = PaintingStyle.stroke, strokeWidth = 0.333f
            });

            canvas.flush();
        }
예제 #33
0
        void drawPloygon4()
        {
            var canvas = new CommandBufferCanvas(this._renderTexture, Window.instance.devicePixelRatio,
                                                 this._meshPool);

            var paint = new Paint {
                color  = new Color(0xFFFF0000),
                shader = Gradient.linear(new Offset(80, 80), new Offset(180, 180), new List <Color>()
                {
                    Colors.red, Colors.black, Colors.green
                }, null, TileMode.clamp)
            };

            var path = new Path();

            path.moveTo(10, 150);
            path.lineTo(10, 160);
            path.lineTo(140, 120);
            path.lineTo(110, 180);
            path.winding(PathWinding.clockwise);
            path.close();
            path.addRect(Unity.UIWidgets.ui.Rect.fromLTWH(0, 100, 100, 100));
            path.addRect(Unity.UIWidgets.ui.Rect.fromLTWH(200, 0, 100, 100));
            path.addRRect(RRect.fromRectAndRadius(Unity.UIWidgets.ui.Rect.fromLTWH(150, 100, 30, 30), 10));
            path.addOval(Unity.UIWidgets.ui.Rect.fromLTWH(150, 50, 100, 100));
            path.winding(PathWinding.clockwise);

            if (Event.current.type == EventType.MouseDown)
            {
                var pos = new Offset(
                    Event.current.mousePosition.x,
                    Event.current.mousePosition.y
                    );

                Debug.Log(pos + ": " + path.contains(pos));
            }

            canvas.drawPath(path, paint);

            canvas.rotate(Mathf.PI * 15 / 180);

            canvas.translate(100, 100);

            paint.shader = Gradient.radial(new Offset(80, 80), 100, new List <Color>()
            {
                Colors.red, Colors.black, Colors.green
            }, null, TileMode.clamp);
            canvas.drawPath(path, paint);


            canvas.translate(100, 100);
            paint.shader = Gradient.sweep(new Offset(120, 100), new List <Color>()
            {
                Colors.red, Colors.black, Colors.green, Colors.red,
            }, null, TileMode.clamp, 10 * Mathf.PI / 180, 135 * Mathf.PI / 180);
            canvas.drawPath(path, paint);


            canvas.translate(100, 100);
            //paint.maskFilter = MaskFilter.blur(BlurStyle.normal, 5);
            paint.shader = new ImageShader(new Image(texture6, true), TileMode.mirror);
            canvas.drawPath(path, paint);

            canvas.flush();
        }
예제 #34
0
        public static void DrawSharpCanvas(Canvas canvas, RectF targetFrame, ResizingBehavior resizing, int fillColor, float width, float height)
        {
            // General Declarations
            Paint paint = CacheForSharpCanvas.paint;

            // Resize to Target Frame
            canvas.Save();
            RectF resizedFrame = CacheForSharpCanvas.resizedFrame;

            SharpKit.resizingBehaviorApply(resizing, CacheForSharpCanvas.originalFrame, targetFrame, resizedFrame);
            canvas.Translate(resizedFrame.Left, resizedFrame.Top);
            canvas.Scale(resizedFrame.Width() / 100f, resizedFrame.Height() / 100f);

            // SharpFrame
            RectF sharpFrame = CacheForSharpCanvas.sharpFrame;

            sharpFrame.Set(0f, 0f, width, height);

            // SharpSymbol
            RectF sharpSymbolRect = CacheForSharpCanvas.sharpSymbolRect;

            sharpSymbolRect.Set(0f, 0f, 100f, 100f);
            Path sharpSymbolPath = CacheForSharpCanvas.sharpSymbolPath;

            sharpSymbolPath.Reset();
            sharpSymbolPath.MoveTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.00002f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top, sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.08245f, sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width(), sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width(), sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.46586f, sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.53414f, sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width(), sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width(), sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.91755f, sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height(), sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height());
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height());
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height(), sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.91755f, sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.91755f, sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height(), sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height());
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height());
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height(), sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.91755f, sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.LineTo(sharpFrame.Left, sharpFrame.Top + sharpFrame.Height() * 0.8f);
            sharpSymbolPath.LineTo(sharpFrame.Left, sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.53414f, sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.46586f, sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.LineTo(sharpFrame.Left, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.LineTo(sharpFrame.Left, sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top + sharpFrame.Height() * 0.08245f, sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top, sharpFrame.Left + sharpFrame.Width() * 0.2f, sharpFrame.Top);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top, sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.08245f, sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.2f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.08245f, sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top, sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.8f, sharpFrame.Top + sharpFrame.Height() * 0.00002f);
            sharpSymbolPath.Close();
            sharpSymbolPath.MoveTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.46586f, sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.53414f, sharpFrame.Left + sharpFrame.Width() * 0.4f, sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.LineTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.6f);
            sharpSymbolPath.CubicTo(sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.53414f, sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.46586f, sharpFrame.Left + sharpFrame.Width() * 0.6f, sharpFrame.Top + sharpFrame.Height() * 0.4f);
            sharpSymbolPath.Close();

            paint.Reset();
            paint.Flags = PaintFlags.AntiAlias;
            paint.SetStyle(Paint.Style.Fill);
            paint.Color = new Color(fillColor);
            canvas.DrawPath(sharpSymbolPath, paint);

            canvas.Restore();
        }
예제 #35
0
        private Bitmap CreateBitmap(ShadeInfo shadeInfo)
        {
#if DEBUG
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            var shadow = Bitmap.CreateBitmap(
                shadeInfo.Width,
                shadeInfo.Height,
                Bitmap.Config.Argb8888);

            InternalLogger.Debug(LogTag, () => $"CreateBitmap( shadeInfo: {shadeInfo} )");
            RectF rect = new RectF(
                ShadeInfo.Padding,
                ShadeInfo.Padding,
                shadeInfo.Width - ShadeInfo.Padding,
                shadeInfo.Height - ShadeInfo.Padding);

            using var bitmapCanvas = new Canvas(shadow);
            using var paint        = new Paint { Color = shadeInfo.Color };
            bitmapCanvas.DrawRoundRect(
                rect,
                _cornerRadius,
                _cornerRadius,
                paint);

            if (shadeInfo.BlurRadius < 1)
            {
                return(shadow);
            }

            const int MaxBlur    = 25;
            float     blurAmount = shadeInfo.BlurRadius > MaxRadius ? MaxRadius : shadeInfo.BlurRadius;
            while (blurAmount > 0)
            {
                Allocation input = Allocation.CreateFromBitmap(
                    _renderScript,
                    shadow,
                    Allocation.MipmapControl.MipmapNone,
                    AllocationUsage.Script);
                Allocation          output = Allocation.CreateTyped(_renderScript, input.Type);
                ScriptIntrinsicBlur script = ScriptIntrinsicBlur.Create(_renderScript, Element.U8_4(_renderScript));

                float blurRadius;
                if (blurAmount > MaxBlur)
                {
                    blurRadius  = MaxBlur;
                    blurAmount -= MaxBlur;
                }
                else
                {
                    blurRadius = blurAmount;
                    blurAmount = 0;
                }

                script.SetRadius(blurRadius);
                script.SetInput(input);
                script.ForEach(output);
                output.CopyTo(shadow);
            }
#if DEBUG
            LogPerf(LogTag, stopWatch);
#endif
            return(shadow);
        }
예제 #36
0
        private void Initialize(Context context, IAttributeSet attrs,
                                int defStyle)
        {
            //set defaults first:

            var circleColor           = Resources.GetColor(Resource.Color.progress_default_circle_color);
            var progressColor         = Resources.GetColor(Resource.Color.progress_default_progress_color);
            var pinnedDrawable        = Resource.Drawable.pin_progress_pinned;
            var unpinnedDrawable      = Resource.Drawable.pin_progress_unpinned;
            var shadowDrawable        = Resource.Drawable.pin_progress_shadow;
            var indeterminate         = false;
            var indeterminateInterval = Resources.GetInteger(Resource.Integer.progressbutton_indeterminent_interval);

            var canChecked   = false;
            var canClickable = false;
            var canFocusable = false;

            m_InnerSize = Resources.GetDimensionPixelSize(Resource.Dimension.progress_inner_size);


            if (context != null && attrs != null)
            {
                var a = context.ObtainStyledAttributes(attrs,
                                                       Resource.Styleable.ProgressButton,
                                                       Resource.Attribute.progressButtonStyle,
                                                       Resource.Style.ProgressButton_Pin);

                m_Progress = a.GetInteger(Resource.Styleable.ProgressButton_progress, 0);
                m_Max      = a.GetInteger(Resource.Styleable.ProgressButton_max, 100);

                circleColor      = a.GetColor(Resource.Styleable.ProgressButton_circleColor, circleColor);
                progressColor    = a.GetColor(Resource.Styleable.ProgressButton_progressColor, progressColor);
                pinnedDrawable   = a.GetResourceId(Resource.Styleable.ProgressButton_pinnedDrawable, pinnedDrawable);
                unpinnedDrawable = a.GetResourceId(Resource.Styleable.ProgressButton_unpinnedDrawable, unpinnedDrawable);
                shadowDrawable   = a.GetResourceId(Resource.Styleable.ProgressButton_shadowDrawable, shadowDrawable);

                m_InnerSize = a.GetDimensionPixelSize(Resource.Styleable.ProgressButton_innerSize, 0);
                if (m_InnerSize == 0)
                {
                    m_InnerSize = Resources.GetDimensionPixelSize(Resource.Dimension.progress_inner_size);
                }

                canChecked   = a.GetBoolean(Resource.Styleable.ProgressButton_pinned, canChecked);
                canClickable = a.GetBoolean(Resource.Styleable.ProgressButton_android_clickable, canClickable);
                canFocusable = a.GetBoolean(Resource.Styleable.ProgressButton_android_focusable, canFocusable);

                SetBackgroundDrawable(a.GetDrawable(Resource.Styleable.ProgressButton_android_selectableItemBackground));
                indeterminateInterval = a.GetInteger(Resource.Styleable.ProgressButton_indeterminate_interval, indeterminateInterval);
                indeterminate         = a.GetBoolean(Resource.Styleable.ProgressButton_indeterminate, indeterminate);

                a.Recycle();
            }

            m_PinnedDrawable = Resources.GetDrawable(pinnedDrawable);
            m_PinnedDrawable.SetCallback(this);

            m_UnpinnedDrawable = Resources.GetDrawable(unpinnedDrawable);
            m_UnpinnedDrawable.SetCallback(this);

            m_ShadowDrawable = Resources.GetDrawable(shadowDrawable);
            m_ShadowDrawable.SetCallback(this);

            m_DrawableSize = m_ShadowDrawable.IntrinsicWidth;

            Checked   = canChecked;
            Clickable = canClickable;
            Focusable = canFocusable;

            CirclePaint = new Paint {
                Color = circleColor, AntiAlias = true
            };
            ProgressPaint = new Paint {
                Color = progressColor, AntiAlias = true
            };

            m_IndeterminateInterval = indeterminateInterval;
            Indeterminante          = indeterminate;
        }
예제 #37
0
    public void Snap()
    {
        Paint script = GameObject.Find("PaintManager").GetComponent <Paint>();

        script.snapping = !script.snapping;
    }
예제 #38
0
        protected override void OnDraw(Canvas canvas)
        {
            if (Element != null && Element.Text != null)
            {
                var   density     = DeviceDisplay.MainDisplayInfo.Density;
                float strokeWidth = Convert.ToSingle(Element.StrokeWidth * density);
                float strokeMiter = 10.0f;

                var rect = new Android.Graphics.Rect();
                this.GetDrawingRect(rect);

                float progressAngle = 360 * Convert.ToSingle(Element.Progress / Element.Total);

                float radius = Math.Min(rect.Height(), rect.Width()) / 2 - strokeWidth;

                RectF circleRect = new RectF(
                    rect.ExactCenterX() - radius,
                    rect.ExactCenterY() - radius,
                    rect.ExactCenterX() + radius,
                    rect.ExactCenterY() + radius
                    );

                TextPaint paint = new TextPaint();
                paint.Color    = Element.TextColor.ToAndroid();
                paint.TextSize = Element.TextSize;
                paint.GetTextBounds(Element.Text.ToString(), 0, Element.Text.ToString().Length, rect);
                if (((this.Width / 2) - (Element.TextMargin * 4)) < rect.Width())
                {
                    float ratio = (float)((this.Width / 2) - Element.TextMargin * 4) / (float)rect.Width();
                    paint.TextSize = paint.TextSize * ratio;
                    paint.GetTextBounds(Element.Text.ToString(), 0, Element.Text.ToString().Length, rect);
                }
                int x = this.Width / 2 - rect.CenterX();
                int y = this.Height / 2 - rect.CenterY();

                Paint progressPaint = new Paint(PaintFlags.AntiAlias)
                {
                    StrokeWidth = strokeWidth,
                    StrokeMiter = strokeMiter,
                    Color       = Element.ProgressStrokeColor.ToAndroid()
                };
                progressPaint.SetStyle(Paint.Style.Stroke);

                Paint availablePaint = new Paint(PaintFlags.AntiAlias)
                {
                    StrokeWidth = strokeWidth,
                    StrokeMiter = strokeMiter,
                    Color       = Element.AvailableStrokeColor.ToAndroid()
                };
                availablePaint.SetStyle(Paint.Style.Stroke);

                Paint paintCircle = new Paint(PaintFlags.AntiAlias)
                {
                    Color = Element.FillColor.ToAndroid()
                };

                canvas.DrawArc(circleRect, -90, progressAngle, false, progressPaint);
                canvas.DrawArc(circleRect, -90 + progressAngle, 360 - progressAngle, false, availablePaint);
                canvas.DrawText(Element.Text.ToString(), x, y, paint);
            }
        }
예제 #39
0
        void DrawBackground(ACanvas canvas, int width, int height, CornerRadius cornerRadius, bool pressed)
        {
            using (var paint = new Paint {
                AntiAlias = true
            })
                using (Path.Direction direction = Path.Direction.Cw)
                    using (Paint.Style style = Paint.Style.Fill)
                    {
                        var path = new Path();

                        if (_pancake.Sides != 4)
                        {
                            path = ShapeUtils.CreatePolygonPath(width, height, _pancake.Sides, _pancake.CornerRadius.TopLeft, _pancake.OffsetAngle);
                        }
                        else
                        {
                            float topLeft     = _convertToPixels(cornerRadius.TopLeft);
                            float topRight    = _convertToPixels(cornerRadius.TopRight);
                            float bottomRight = _convertToPixels(cornerRadius.BottomRight);
                            float bottomLeft  = _convertToPixels(cornerRadius.BottomLeft);

                            path = ShapeUtils.CreateRoundedRectPath(width, height, topLeft, topRight, bottomRight, bottomLeft);
                        }

                        if ((_pancake.BackgroundGradientStartColor != default(Xamarin.Forms.Color) && _pancake.BackgroundGradientEndColor != default(Xamarin.Forms.Color)) || (_pancake.BackgroundGradientStops != null && _pancake.BackgroundGradientStops.Any()))
                        {
                            var angle = _pancake.BackgroundGradientAngle / 360.0;

                            // Calculate the new positions based on angle between 0-360.
                            var a = width * Math.Pow(Math.Sin(2 * Math.PI * ((angle + 0.75) / 2)), 2);
                            var b = height * Math.Pow(Math.Sin(2 * Math.PI * ((angle + 0.0) / 2)), 2);
                            var c = width * Math.Pow(Math.Sin(2 * Math.PI * ((angle + 0.25) / 2)), 2);
                            var d = height * Math.Pow(Math.Sin(2 * Math.PI * ((angle + 0.5) / 2)), 2);

                            if (_pancake.BackgroundGradientStops != null && _pancake.BackgroundGradientStops.Count > 0)
                            {
                                // A range of colors is given. Let's add them.
                                var orderedStops = _pancake.BackgroundGradientStops.OrderBy(x => x.Offset).ToList();
                                var colors       = orderedStops.Select(x => x.Color.ToAndroid().ToArgb()).ToArray();
                                var locations    = orderedStops.Select(x => x.Offset).ToArray();

                                var shader = new LinearGradient(width - (float)a, (float)b, width - (float)c, (float)d, colors, locations, Shader.TileMode.Clamp);
                                paint.SetShader(shader);
                            }
                            else
                            {
                                // Only two colors provided, use that.
                                var shader = new LinearGradient(width - (float)a, (float)b, width - (float)c, (float)d, _pancake.BackgroundGradientStartColor.ToAndroid(), _pancake.BackgroundGradientEndColor.ToAndroid(), Shader.TileMode.Clamp);
                                paint.SetShader(shader);
                            }
                        }
                        else
                        {
                            global::Android.Graphics.Color color = _pancake.BackgroundColor.ToAndroid();
                            paint.SetStyle(style);
                            paint.Color = color;
                        }

                        canvas.DrawPath(path, paint);
                    }
        }
예제 #40
0
        public override void debugPaint(PaintingContext context, Offset offset)
        {
            D.assert(() => {
                if (D.debugPaintSizeEnabled)
                {
                    float strokeWidth = Mathf.Min(4.0f, this.geometry.paintExtent / 30.0f);
                    Paint paint       = new Paint();
//          ..color = const Color(0xFF33CC33)
//          ..strokeWidth = strokeWidth
//          ..style = PaintingStyle.stroke
//          ..maskFilter = new MaskFilter.blur(BlurStyle.solid, strokeWidth);
                    float arrowExtent = this.geometry.paintExtent;
                    float padding     = Mathf.Max(2.0f, strokeWidth);
                    Canvas canvas     = context.canvas;
//        canvas.drawCircle(
//          offset.translate(padding, padding),
//          padding * 0.5,
//          paint,
//        );
                    switch (this.constraints.axis)
                    {
                    case Axis.vertical:
//            canvas.drawLine(
//              offset,
//              offset.translate(constraints.crossAxisExtent, 0.0f),
//              paint,
//            );
                        this._debugDrawArrow(
                            canvas,
                            paint,
                            offset.translate(this.constraints.crossAxisExtent * 1.0f / 4.0f, padding),
                            offset.translate(this.constraints.crossAxisExtent * 1.0f / 4.0f,
                                             (arrowExtent - padding)),
                            this.constraints.normalizedGrowthDirection
                            );
                        this._debugDrawArrow(
                            canvas,
                            paint,
                            offset.translate(this.constraints.crossAxisExtent * 3.0f / 4.0f, padding),
                            offset.translate(this.constraints.crossAxisExtent * 3.0f / 4.0f,
                                             (arrowExtent - padding)),
                            this.constraints.normalizedGrowthDirection
                            );
                        break;

                    case Axis.horizontal:
//            canvas.drawLine(
//              offset,
//              offset.translate(0.0f, constraints.crossAxisExtent),
//              paint,
//            );
                        this._debugDrawArrow(
                            canvas,
                            paint,
                            offset.translate(padding, this.constraints.crossAxisExtent * 1.0f / 4.0f),
                            offset.translate((arrowExtent - padding),
                                             this.constraints.crossAxisExtent * 1.0f / 4.0f),
                            this.constraints.normalizedGrowthDirection
                            );
                        this._debugDrawArrow(
                            canvas,
                            paint,
                            offset.translate(padding, this.constraints.crossAxisExtent * 3.0f / 4.0f),
                            offset.translate((arrowExtent - padding),
                                             this.constraints.crossAxisExtent * 3.0f / 4.0f),
                            this.constraints.normalizedGrowthDirection
                            );
                        break;
                    }
                }

                return(true);
            });
        }
예제 #41
0
파일: CheckBox.Impl.cs 프로젝트: hevey/maui
 void IMapColorPropertyToPaint.MapColorPropertyToPaint(Color color)
 {
     Foreground = color?.AsPaint();
 }
예제 #42
0
        public static Bitmap ToTransformedCorners(Bitmap source, double topLeftCornerSize, double topRightCornerSize, double bottomLeftCornerSize, double bottomRightCornerSize,
                                                  CornerTransformType cornersTransformType, 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);
            }

            topLeftCornerSize     = topLeftCornerSize * (desiredWidth + desiredHeight) / 2 / 100;
            topRightCornerSize    = topRightCornerSize * (desiredWidth + desiredHeight) / 2 / 100;
            bottomLeftCornerSize  = bottomLeftCornerSize * (desiredWidth + desiredHeight) / 2 / 100;
            bottomRightCornerSize = bottomRightCornerSize * (desiredWidth + desiredHeight) / 2 / 100;

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

            Bitmap bitmap = Bitmap.CreateBitmap((int)desiredWidth, (int)desiredHeight, Bitmap.Config.Argb8888);

            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())
                            using (var path = new Path())
                            {
                                if (cropX != 0 || cropY != 0)
                                {
                                    matrix.SetTranslate(-cropX, -cropY);
                                    shader.SetLocalMatrix(matrix);
                                }

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

                                // TopLeft
                                if (cornersTransformType.HasFlag(CornerTransformType.TopLeftCut))
                                {
                                    path.MoveTo(0, (float)topLeftCornerSize);
                                    path.LineTo((float)topLeftCornerSize, 0);
                                }
                                else if (cornersTransformType.HasFlag(CornerTransformType.TopLeftRounded))
                                {
                                    path.MoveTo(0, (float)topLeftCornerSize);
                                    path.QuadTo(0, 0, (float)topLeftCornerSize, 0);
                                }
                                else
                                {
                                    path.MoveTo(0, 0);
                                }

                                // TopRight
                                if (cornersTransformType.HasFlag(CornerTransformType.TopRightCut))
                                {
                                    path.LineTo((float)(desiredWidth - topRightCornerSize), 0);
                                    path.LineTo((float)desiredWidth, (float)topRightCornerSize);
                                }
                                else if (cornersTransformType.HasFlag(CornerTransformType.TopRightRounded))
                                {
                                    path.LineTo((float)(desiredWidth - topRightCornerSize), 0);
                                    path.QuadTo((float)desiredWidth, 0, (float)desiredWidth, (float)topRightCornerSize);
                                }
                                else
                                {
                                    path.LineTo((float)desiredWidth, 0);
                                }

                                // BottomRight
                                if (cornersTransformType.HasFlag(CornerTransformType.BottomRightCut))
                                {
                                    path.LineTo((float)desiredWidth, (float)(desiredHeight - bottomRightCornerSize));
                                    path.LineTo((float)(desiredWidth - bottomRightCornerSize), (float)desiredHeight);
                                }
                                else if (cornersTransformType.HasFlag(CornerTransformType.BottomRightRounded))
                                {
                                    path.LineTo((float)desiredWidth, (float)(desiredHeight - bottomRightCornerSize));
                                    path.QuadTo((float)desiredWidth, (float)desiredHeight, (float)(desiredWidth - bottomRightCornerSize), (float)desiredHeight);
                                }
                                else
                                {
                                    path.LineTo((float)desiredWidth, (float)desiredHeight);
                                }

                                // BottomLeft
                                if (cornersTransformType.HasFlag(CornerTransformType.BottomLeftCut))
                                {
                                    path.LineTo((float)bottomLeftCornerSize, (float)desiredHeight);
                                    path.LineTo(0, (float)(desiredHeight - bottomLeftCornerSize));
                                }
                                else if (cornersTransformType.HasFlag(CornerTransformType.BottomLeftRounded))
                                {
                                    path.LineTo((float)bottomLeftCornerSize, (float)desiredHeight);
                                    path.QuadTo(0, (float)desiredHeight, 0, (float)(desiredHeight - bottomLeftCornerSize));
                                }
                                else
                                {
                                    path.LineTo(0, (float)desiredHeight);
                                }

                                path.Close();
                                canvas.DrawPath(path, paint);

                                return(bitmap);
                            }
        }
예제 #43
0
        /// <summary>
        /// We use this method to draw the control according to property values
        /// </summary>
        /// <param name="canvas">The canvas on which the control will be drawn</param>
        protected override void OnDraw(Canvas canvas)
        {
            var element = this.Element;

            float centerX     = 0;
            float centerY     = 0;
            float radius      = 0;
            float strokeWidth = 30;

            float horizontalOffSet;
            float verticalOffSet;

            centerX = (float)canvas.Width / 2;
            centerY = (float)canvas.Height / 2;

            if (canvas.Width > canvas.Height)
            {
                strokeWidth      = (float)canvas.Height / 20;
                radius           = (float)canvas.Height / 2 - strokeWidth;
                horizontalOffSet = (float)canvas.Width / 2 - (float)canvas.Height / 2 + strokeWidth + strokeWidth / 2;
                verticalOffSet   = strokeWidth + strokeWidth / 2;
            }
            else
            {
                strokeWidth      = (float)canvas.Width / 20;
                radius           = (float)canvas.Width / 2 - strokeWidth;
                verticalOffSet   = (float)canvas.Height / 2 - (float)canvas.Width / 2 + strokeWidth + strokeWidth / 2;
                horizontalOffSet = strokeWidth + strokeWidth / 2;
            }
            var progress    = element.Progress;
            var borderColor = element.BorderColor.ToAndroid();

            if (progress >= element.Max)
            {
                borderColor = element.MaxReachedBorderColor.ToAndroid();
            }
            var fillColor = element.FillColor.ToAndroid();
            var paint     = new Paint();

            // draw border circle
            paint.Color       = borderColor;
            paint.StrokeWidth = strokeWidth;
            paint.AntiAlias   = true;
            paint.SetStyle(Paint.Style.Stroke);
            canvas.DrawCircle(centerX, centerY, radius, paint);
            // draw progress circle
            paint.Color = fillColor;
            var oval = new RectF();

            paint.SetStyle(Paint.Style.Fill);
            var   progressRadialPercentage = (float)(progress * 360) / element.Max;
            float startAngle = 270;

            oval.Set(horizontalOffSet, verticalOffSet, canvas.Width - horizontalOffSet, canvas.Height - verticalOffSet);
            canvas.DrawArc(oval, startAngle, progressRadialPercentage, true, paint);
            // draw progress text
            paint.StrokeWidth = 1;
            paint.TextSize    = (radius * 2) / 3;
            paint.TextAlign   = Paint.Align.Center;
            paint.Color       = element.TextColor.ToAndroid();

            var displayText = string.Empty;

            if (element.DisplayMode == DisplayModeTypes.ShowProgress)
            {
                displayText = progress.ToString();
            }
            else if (element.DisplayMode == DisplayModeTypes.ShowPercentage)
            {
                displayText = ((float)(progress * 100) / element.Max) + "%";
            }
            canvas.DrawText(displayText, centerX, centerY + (paint.TextSize / 3), paint);
            var mainTextPosition = centerY + (paint.TextSize / 3);

            // draw custom message
            paint.TextSize = (radius * 2) / 10;
            canvas.DrawText(element.ProgressText, centerX, mainTextPosition + paint.TextSize + 2, paint);
        }
예제 #44
0
        protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
        {
            bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd);

            const double wheelDelta = 120.0;
            uint         timestamp  = unchecked ((uint)UnmanagedMethods.GetMessageTime());

            RawInputEventArgs e = null;

            WindowsMouseDevice.Instance.CurrentWindow = this;

            switch ((UnmanagedMethods.WindowsMessage)msg)
            {
            case UnmanagedMethods.WindowsMessage.WM_ACTIVATE:
                var wa = (UnmanagedMethods.WindowActivate)(ToInt32(wParam) & 0xffff);

                switch (wa)
                {
                case UnmanagedMethods.WindowActivate.WA_ACTIVE:
                case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE:
                    _isActive = true;
                    Activated?.Invoke();
                    break;

                case UnmanagedMethods.WindowActivate.WA_INACTIVE:
                    _isActive = false;
                    Deactivated?.Invoke();
                    break;
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_DESTROY:
                if (Closed != null)
                {
                    UnmanagedMethods.UnregisterClass(_className, Marshal.GetHINSTANCE(GetType().Module));
                    Closed();
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_DPICHANGED:
                var dpi            = ToInt32(wParam) & 0xffff;
                var newDisplayRect = (UnmanagedMethods.RECT)Marshal.PtrToStructure(lParam, typeof(UnmanagedMethods.RECT));
                Position = new Point(newDisplayRect.left, newDisplayRect.top);
                _scaling = dpi / 96.0;
                ScalingChanged?.Invoke(_scaling);
                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_KEYDOWN:
            case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN:
                e = new RawKeyEventArgs(
                    WindowsKeyboardDevice.Instance,
                    timestamp,
                    RawKeyEventType.KeyDown,
                    KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_KEYUP:
            case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP:
                e = new RawKeyEventArgs(
                    WindowsKeyboardDevice.Instance,
                    timestamp,
                    RawKeyEventType.KeyUp,
                    KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_CHAR:
                // Ignore control chars
                if (ToInt32(wParam) >= 32)
                {
                    e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp,
                                                  new string((char)ToInt32(wParam), 1));
                }

                break;

            case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN
                            ? RawMouseEventType.LeftButtonDown
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN
                                ? RawMouseEventType.RightButtonDown
                                : RawMouseEventType.MiddleButtonDown,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP:
            case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP:
            case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONUP
                            ? RawMouseEventType.LeftButtonUp
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONUP
                                ? RawMouseEventType.RightButtonUp
                                : RawMouseEventType.MiddleButtonUp,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE:
                if (!_trackingMouse)
                {
                    var tm = new UnmanagedMethods.TRACKMOUSEEVENT
                    {
                        cbSize      = Marshal.SizeOf(typeof(UnmanagedMethods.TRACKMOUSEEVENT)),
                        dwFlags     = 2,
                        hwndTrack   = _hwnd,
                        dwHoverTime = 0,
                    };

                    UnmanagedMethods.TrackMouseEvent(ref tm);
                }

                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    RawMouseEventType.Move,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));

                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL:
                e = new RawMouseWheelEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    ScreenToClient(DipFromLParam(lParam)),
                    new Vector(0, (ToInt32(wParam) >> 16) / wheelDelta), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEHWHEEL:
                e = new RawMouseWheelEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    ScreenToClient(DipFromLParam(lParam)),
                    new Vector(-(ToInt32(wParam) >> 16) / wheelDelta, 0), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE:
                _trackingMouse = false;
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    RawMouseEventType.LeaveWindow,
                    new Point(), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN
                            ? RawMouseEventType.NonClientLeftButtonDown
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN
                                ? RawMouseEventType.RightButtonDown
                                : RawMouseEventType.MiddleButtonDown,
                    new Point(0, 0), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_PAINT:
                UnmanagedMethods.PAINTSTRUCT ps;

                if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero)
                {
                    UnmanagedMethods.RECT r;
                    UnmanagedMethods.GetUpdateRect(_hwnd, out r, false);
                    var f = Scaling;
                    Paint?.Invoke(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f));
                    UnmanagedMethods.EndPaint(_hwnd, ref ps);
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_SIZE:
                if (Resized != null &&
                    (wParam == (IntPtr)UnmanagedMethods.SizeCommand.Restored ||
                     wParam == (IntPtr)UnmanagedMethods.SizeCommand.Maximized))
                {
                    var clientSize = new Size(ToInt32(lParam) & 0xffff, ToInt32(lParam) >> 16);
                    Resized(clientSize / Scaling);
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_MOVE:
                PositionChanged?.Invoke(new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)));
                return(IntPtr.Zero);
            }

            if (e != null && Input != null)
            {
                Input(e);

                if (e.Handled)
                {
                    return(IntPtr.Zero);
                }
            }

            return(UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam));
        }
예제 #45
0
        /// <summary>
        /// Calculates the dimensions of the Legend. This includes the maximum width
        /// and height of a single entry, as well as the total width and height of
        /// the Legend.
        public void CalculateDimensions(Paint paint, ViewPortHandler viewPortHandler)
        {
            var   maxEntrySize    = GetMaximumEntrySize(paint);
            float defaultFormSize = FormSize.DpToPixel();
            float stackSpace      = StackSpace.DpToPixel();
            float formToTextSpace = FormToTextSpace.DpToPixel();
            float xEntrySpace     = XEntrySpace.DpToPixel();
            float yEntrySpace     = YEntrySpace.DpToPixel();
            var   wordWrapEnabled = WordWrapEnabled;
            var   entries         = Entries;
            int   entryCount      = entries.Count;

            TextWidthMax  = maxEntrySize.Width;
            TextHeightMax = maxEntrySize.Height;

            switch (Orientation)
            {
            case Orientation.Vertical:
            {
                float maxWidth = 0f, maxHeight = 0f, width = 0f;
                float labelLineHeight = paint.LineHeight();
                bool  wasStacked      = false;

                for (int i = 0; i < entryCount; i++)
                {
                    LegendEntry e           = entries[i];
                    var         drawingForm = e.Form != Form.None;
                    float       formSize    = float.IsNaN(e.FormSize)
                                    ? defaultFormSize
                                    : e.FormSize.DpToPixel();
                    var label = e.Label;
                    if (!wasStacked)
                    {
                        width = 0.0f;
                    }

                    if (drawingForm)
                    {
                        if (wasStacked)
                        {
                            width += stackSpace;
                        }
                        width += formSize;
                    }

                    // grouped forms have null labels
                    if (label != null)
                    {
                        var size = paint.MeasureWidth(label);
                        // make a step to the left
                        if (drawingForm && !wasStacked)
                        {
                            width += formToTextSpace;
                        }
                        else if (wasStacked)
                        {
                            maxWidth   = Math.Max(maxWidth, width);
                            maxHeight += labelLineHeight + yEntrySpace;
                            width      = 0.0f;
                            wasStacked = false;
                        }

                        width += size;

                        maxHeight += labelLineHeight + yEntrySpace;
                    }
                    else
                    {
                        wasStacked = true;
                        width     += formSize;
                        if (i < entryCount - 1)
                        {
                            width += stackSpace;
                        }
                    }

                    maxWidth = Math.Max(maxWidth, width);
                }

                NeededWidth  = maxWidth;
                NeededHeight = maxHeight;

                break;
            }

            case Orientation.Horizontal:
            {
                float labelLineHeight  = paint.LineHeight();
                float labelLineSpacing = paint.LineSpacing() + yEntrySpace;
                float contentWidth     = viewPortHandler.ContentWidth * MaxSizePercent;

                // Start calculating layout
                float maxLineWidth      = 0.0f;
                float currentLineWidth  = 0.0f;
                float requiredWidth     = 0.0f;
                int   stackedStartIndex = -1;

                CalculatedLabelBreakPoints.Clear();
                CalculatedLabelSizes.Clear();
                CalculatedLineSizes.Clear();

                for (int i = 0; i < entryCount; i++)
                {
                    LegendEntry e           = entries[i];
                    var         drawingForm = e.Form != Form.None;
                    float       formSize    = float.IsNaN(e.FormSize)
                                    ? defaultFormSize
                                    : e.FormSize.DpToPixel();
                    var label = e.Label;

                    CalculatedLabelBreakPoints.Add(false);

                    if (stackedStartIndex == -1)
                    {
                        // we are not stacking, so required width is for this label
                        // only
                        requiredWidth = 0.0f;
                    }
                    else
                    {
                        // add the spacing appropriate for stacked labels/forms
                        requiredWidth += stackSpace;
                    }

                    // grouped forms have null labels
                    if (label != null)
                    {
                        CalculatedLabelSizes.Add(paint.Measure(label));
                        requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0f;
                        requiredWidth += CalculatedLabelSizes[i].Width;
                    }
                    else
                    {
                        CalculatedLabelSizes.Add(new ChartSize(0, 0));
                        requiredWidth += drawingForm ? formSize : 0.0f;

                        if (stackedStartIndex == -1)
                        {
                            // mark this index as we might want to break here later
                            stackedStartIndex = i;
                        }
                    }

                    if (label != null || i == entryCount - 1)
                    {
                        float requiredSpacing = currentLineWidth == 0.0f ? 0.0f : xEntrySpace;

                        if (!wordWrapEnabled         // No word wrapping, it must fit.
                                                     // The line is empty, it must fit
                            || currentLineWidth == 0.0f
                            // It simply fits
                            || (contentWidth - currentLineWidth >=
                                requiredSpacing + requiredWidth))
                        {
                            // Expand current line
                            currentLineWidth += requiredSpacing + requiredWidth;
                        }
                        else
                        {         // It doesn't fit, we need to wrap a line
                            // Add current line size to array
                            CalculatedLineSizes.Add(new ChartSize(currentLineWidth, labelLineHeight));
                            maxLineWidth = Math.Max(maxLineWidth, currentLineWidth);

                            // Start a new line
                            CalculatedLabelBreakPoints.Insert(
                                stackedStartIndex > -1 ? stackedStartIndex
                                                    : i, true);
                            currentLineWidth = requiredWidth;
                        }

                        if (i == entryCount - 1)
                        {
                            // Add last line size to array
                            CalculatedLineSizes.Add(new ChartSize(currentLineWidth, labelLineHeight));
                            maxLineWidth = Math.Max(maxLineWidth, currentLineWidth);
                        }
                    }

                    stackedStartIndex = label != null ? -1 : stackedStartIndex;
                }

                NeededWidth  = maxLineWidth;
                NeededHeight = labelLineHeight
                               * (float)(CalculatedLineSizes.Count)
                               + labelLineSpacing *
                               (float)(CalculatedLineSizes.Count == 0
                                        ? 0
                                        : (CalculatedLineSizes.Count - 1));

                break;
            }
            }

            NeededHeight += YOffset;
            NeededWidth  += XOffset;
        }
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            int hourHeight = mHourHeight;

            Paint dividerPaint = mDividerPaint;

            dividerPaint.Color = mDividerColor;
            dividerPaint.SetStyle(Paint.Style.Fill);

            Paint labelPaint = mLabelPaint;

            labelPaint.Color    = mLabelColor;
            labelPaint.TextSize = mLabelTextSize;
            labelPaint.SetTypeface(Typeface.DefaultBold);
            labelPaint.AntiAlias = true;

            var metrics     = labelPaint.GetFontMetricsInt();
            int labelHeight = Math.Abs(metrics.Ascent);
            int labelOffset = labelHeight + mLabelPaddingLeft;

            int right = Right;

            // Walk left side of canvas drawing timestamps
            int hours = mEndHour - mStartHour;

            for (int i = 0; i < hours; i++)
            {
                int dividerY     = hourHeight * i;
                int nextDividerY = hourHeight * (i + 1);
                canvas.DrawLine(0, dividerY, right, dividerY, dividerPaint);

                // draw text title for timestamp
                canvas.DrawRect(0, dividerY, mHeaderWidth, nextDividerY, dividerPaint);

                // TODO: localize these labels better, including handling
                // 24-hour mode when set in framework.
                int    hour = mStartHour + i;
                String label;
                if (hour == 0)
                {
                    label = "12am";
                }
                else if (hour <= 11)
                {
                    label = hour + "am";
                }
                else if (hour == 12)
                {
                    label = "12pm";
                }
                else
                {
                    label = (hour - 12) + "pm";
                }

                float labelWidth = labelPaint.MeasureText(label);

                canvas.DrawText(label, 0, label.Length, mHeaderWidth - labelWidth - mLabelPaddingLeft, dividerY + labelOffset, labelPaint);
            }
        }
예제 #47
0
 void Draw()
 {
     Paint?.Invoke(new Rect(new Point(0, 0), ClientSize));
 }
예제 #48
0
 public Layers(Context context)
     : base(context)
 {
     mPaint = new Paint();
     mPaint.setAntiAlias(true);
 }
예제 #49
0
        public static int calculateWidthFromFontSize(String testString, int currentSize, Paint paint)
        {
            Rect bounds = new Rect();

            paint.TextSize = GetScrX(currentSize);
            paint.GetTextBounds(testString, 0, testString.Length, bounds);

            return((int)Math.Ceiling((double)bounds.Width()));
        }
예제 #50
0
 internal DrawMetrics(Paint textPaint)
 {
     this.textPaint = textPaint;
     Invalidate();
 }
예제 #51
0
        void saveLayer()
        {
            var pictureRecorder = new PictureRecorder();
            var canvas          = new RecorderCanvas(pictureRecorder);

            var paint = new Paint {
                color = new Color(0xFFFF0000),
            };

            var path = new Path();

            path.moveTo(10, 10);
            path.lineTo(10, 110);
            path.lineTo(90, 110);
            path.lineTo(110, 10);
            path.close();

            canvas.drawPath(path, paint);

            paint = new Paint {
                color = new Color(0xFFFFFF00),
            };

            var rect   = Unity.UIWidgets.ui.Rect.fromLTWH(10, 150, 100, 100);
            var rrect  = RRect.fromRectAndCorners(rect, 0, 4, 8, 16);
            var rect1  = Unity.UIWidgets.ui.Rect.fromLTWH(18, 152, 88, 92);
            var rrect1 = RRect.fromRectAndCorners(rect1, 0, 4, 8, 16);

            canvas.drawDRRect(rrect, rrect1, paint);

            canvas.rotate(-45 * Mathf.PI / 180.0f, new Offset(150, 150));

//            paint = new Paint {
//                color = new Color(0xFF00FFFF),
//                blurSigma = 3,
//            };
//            canvas.drawRectShadow(
//                Rect.fromLTWH(150, 150, 110, 120),
//                paint);

            var picture = pictureRecorder.endRecording();

            Debug.Log("picture.paintBounds: " + picture.paintBounds);

            var editorCanvas = new CommandBufferCanvas(this._renderTexture, Window.instance.devicePixelRatio,
                                                       this._meshPool);

            editorCanvas.saveLayer(picture.paintBounds, new Paint {
                color = new Color(0x7FFFFFFF)
            });
            editorCanvas.drawPicture(picture);
            editorCanvas.restore();

            editorCanvas.translate(150, 0);
            editorCanvas.saveLayer(picture.paintBounds, new Paint {
                color = new Color(0xFFFFFFFF)
            });
            editorCanvas.drawPicture(picture);
            editorCanvas.restore();

            editorCanvas.flush();
        }
예제 #52
0
        protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
        {
            bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd);

            const double wheelDelta = 120.0;
            uint         timestamp  = unchecked ((uint)UnmanagedMethods.GetMessageTime());

            RawInputEventArgs e = null;

            WindowsMouseDevice.Instance.CurrentWindow = this;

            switch ((UnmanagedMethods.WindowsMessage)msg)
            {
            case UnmanagedMethods.WindowsMessage.WM_ACTIVATE:
                var wa = (UnmanagedMethods.WindowActivate)(ToInt32(wParam) & 0xffff);

                switch (wa)
                {
                case UnmanagedMethods.WindowActivate.WA_ACTIVE:
                case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE:
                    Activated?.Invoke();
                    break;

                case UnmanagedMethods.WindowActivate.WA_INACTIVE:
                    Deactivated?.Invoke();
                    break;
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_DESTROY:
                //Window doesn't exist anymore
                _hwnd = IntPtr.Zero;
                //Remove root reference to this class, so unmanaged delegate can be collected
                s_instances.Remove(this);
                Closed?.Invoke();
                //Free other resources
                Dispose();
                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_DPICHANGED:
                var dpi            = ToInt32(wParam) & 0xffff;
                var newDisplayRect = Marshal.PtrToStructure <UnmanagedMethods.RECT>(lParam);
                Position = new Point(newDisplayRect.left, newDisplayRect.top);
                _scaling = dpi / 96.0;
                ScalingChanged?.Invoke(_scaling);
                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_KEYDOWN:
            case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN:
                e = new RawKeyEventArgs(
                    WindowsKeyboardDevice.Instance,
                    timestamp,
                    RawKeyEventType.KeyDown,
                    KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_KEYUP:
            case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP:
                e = new RawKeyEventArgs(
                    WindowsKeyboardDevice.Instance,
                    timestamp,
                    RawKeyEventType.KeyUp,
                    KeyInterop.KeyFromVirtualKey(ToInt32(wParam)), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_CHAR:
                // Ignore control chars
                if (ToInt32(wParam) >= 32)
                {
                    e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp,
                                                  new string((char)ToInt32(wParam), 1));
                }

                break;

            case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN
                            ? RawMouseEventType.LeftButtonDown
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN
                                ? RawMouseEventType.RightButtonDown
                                : RawMouseEventType.MiddleButtonDown,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP:
            case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP:
            case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONUP
                            ? RawMouseEventType.LeftButtonUp
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONUP
                                ? RawMouseEventType.RightButtonUp
                                : RawMouseEventType.MiddleButtonUp,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE:
                if (!_trackingMouse)
                {
                    var tm = new UnmanagedMethods.TRACKMOUSEEVENT
                    {
                        cbSize      = Marshal.SizeOf <UnmanagedMethods.TRACKMOUSEEVENT>(),
                        dwFlags     = 2,
                        hwndTrack   = _hwnd,
                        dwHoverTime = 0,
                    };

                    UnmanagedMethods.TrackMouseEvent(ref tm);
                }

                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    RawMouseEventType.Move,
                    DipFromLParam(lParam), GetMouseModifiers(wParam));

                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL:
                e = new RawMouseWheelEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    PointToClient(PointFromLParam(lParam)),
                    new Vector(0, (ToInt32(wParam) >> 16) / wheelDelta), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSEHWHEEL:
                e = new RawMouseWheelEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    PointToClient(PointFromLParam(lParam)),
                    new Vector(-(ToInt32(wParam) >> 16) / wheelDelta, 0), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE:
                _trackingMouse = false;
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    RawMouseEventType.LeaveWindow,
                    new Point(), WindowsKeyboardDevice.Instance.Modifiers);
                break;

            case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN:
            case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN:
                e = new RawMouseEventArgs(
                    WindowsMouseDevice.Instance,
                    timestamp,
                    _owner,
                    msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN
                            ? RawMouseEventType.NonClientLeftButtonDown
                            : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN
                                ? RawMouseEventType.RightButtonDown
                                : RawMouseEventType.MiddleButtonDown,
                    new Point(0, 0), GetMouseModifiers(wParam));
                break;

            case UnmanagedMethods.WindowsMessage.WM_PAINT:
                UnmanagedMethods.PAINTSTRUCT ps;

                if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero)
                {
                    var f = Scaling;
                    var r = ps.rcPaint;
                    Paint?.Invoke(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f));
                    UnmanagedMethods.EndPaint(_hwnd, ref ps);
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_SIZE:
                if (Resized != null &&
                    (wParam == (IntPtr)UnmanagedMethods.SizeCommand.Restored ||
                     wParam == (IntPtr)UnmanagedMethods.SizeCommand.Maximized))
                {
                    var clientSize = new Size(ToInt32(lParam) & 0xffff, ToInt32(lParam) >> 16);
                    Resized(clientSize / Scaling);
                }

                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_MOVE:
                PositionChanged?.Invoke(new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)));
                return(IntPtr.Zero);

            case UnmanagedMethods.WindowsMessage.WM_DISPLAYCHANGE:
                (Screen as ScreenImpl)?.InvalidateScreensCache();
                return(IntPtr.Zero);
            }
#if USE_MANAGED_DRAG
            if (_managedDrag.PreprocessInputEvent(ref e))
            {
                return(UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam));
            }
#endif

            if (e != null && Input != null)
            {
                Input(e);

                if (e.Handled)
                {
                    return(IntPtr.Zero);
                }
            }

            return(UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam));
        }
 public abstract void ClearGradient(Paint paint, int width, int height);
예제 #54
0
 public abstract void Apply(StrokeStyle StrokeStyle, Paint paint);
        /// <summary>
        ///
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="child"></param>
        /// <param name="drawingTime"></param>
        /// <returns></returns>
        protected override bool DrawChild(Canvas canvas, Android.Views.View child, long drawingTime)
        {
            try
            {
                var radius = Math.Min(Width, Height) / 2;

                var borderThickness = (float)((IconAwesomeButtonBase)Element).BorderThickness;

                int strokeWidth = 0;

                if (borderThickness > 0)
                {
                    var logicalDensity = context.Resources.DisplayMetrics.Density;
                    strokeWidth = (int)Math.Ceiling(borderThickness * logicalDensity + .5f);
                }

                radius -= strokeWidth / 2;

                var path = new Path();
                path.AddCircle(Width / 2.0f, Height / 2.0f, radius, Path.Direction.Ccw);

                canvas.Save();
                canvas.ClipPath(path);

                var paint = new Paint
                {
                    AntiAlias = true,
                    Color     = ((IconAwesomeButtonBase)Element).BackgroundColor.ToAndroid()
                };
                paint.SetStyle(Paint.Style.Fill);
                canvas.DrawPath(path, paint);
                paint.Dispose();

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

                path.Dispose();
                canvas.Restore();

                path = new Path();
                path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);

                if (strokeWidth > 0.0f)
                {
                    paint = new Paint
                    {
                        AntiAlias   = true,
                        StrokeWidth = strokeWidth
                    };
                    paint.SetStyle(Paint.Style.Stroke);
                    paint.Color = ((IconAwesomeButtonBase)Element).BorderColor.ToAndroid();
                    canvas.DrawPath(path, paint);
                    paint.Dispose();
                }

                path.Dispose();
                return(result);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create circle button: " + ex);
            }

            return(base.DrawChild(canvas, child, drawingTime));
        }
예제 #56
0
            public View GetView(int position, View convertView, ViewGroup parent)
            {
                ViewHolder viewHolder;

                if (convertView == null)
                {
                    LayoutInflater inflater = LayoutInflater.From(parent.Context);
                    convertView = inflater.Inflate(layout, parent, false);
                    viewHolder  = new ViewHolder();

                    viewHolder.ivFullImage        = (ImageView)convertView.FindViewById(Resource.Id.ivFullImage);
                    viewHolder.ivCroppedImage     = (ImageView)convertView.FindViewById(Resource.Id.ivCroppedImage);
                    viewHolder.tvSizeFullImage    = convertView.FindViewById <TextView>(Resource.Id.tvSizeFullImage);
                    viewHolder.tvSizeCroppedImage = convertView.FindViewById <TextView>(Resource.Id.tvSizeCroppedImage);

                    convertView.Tag = viewHolder;
                }
                else
                {
                    viewHolder = (ViewHolder)convertView.Tag;
                }

                // the tag will be used to retrieve the actual position in the list when clicking on an image:
                viewHolder.ivFullImage.Tag    = position;
                viewHolder.ivCroppedImage.Tag = position;

                //values[position] = "";
                fullImgFile = null;
                if (fullImagePath[position] != null)
                { // values[position] contains the path of the full image
                    fullImgFile = new File(fullImagePath[position]);
                    if (fullImgFile.Exists())
                    {
                        // create bitmap in ARGB-format from full image file:
                        Bitmap fullBitmap         = BitmapFactory.DecodeFile(fullImgFile.AbsolutePath);
                        Bitmap drawableFullBitmap = fullBitmap.Copy(Bitmap.Config.Argb8888, true);

                        // draw small red circles on the fullBitmap, indicating the corners:
                        if (Corners[position] != null)
                        {
                            Canvas canvas = new Canvas(drawableFullBitmap);
                            Paint  paint  = new Paint();
                            paint.Color       = Color.Red;
                            paint.StrokeWidth = 4;
                            canvas.DrawBitmap(drawableFullBitmap, new Matrix(), null);
                            canvas.DrawCircle(Corners[position][0].X, Corners[position][0].Y, 12, paint);
                            canvas.DrawCircle(Corners[position][1].X, Corners[position][1].Y, 12, paint);
                            canvas.DrawCircle(Corners[position][2].X, Corners[position][2].Y, 12, paint);
                            canvas.DrawCircle(Corners[position][3].X, Corners[position][3].Y, 12, paint);
                        }

                        // display the full image with the 4 corners:
                        viewHolder.ivFullImage.SetImageBitmap(drawableFullBitmap);

                        // display the size (height and width) of the full image:
                        viewHolder.tvSizeFullImage.SetText(getPictureResolution(parent.Context, fullImagePath[position]), TextView.BufferType.Normal);

                        // if user clicks on full image: call cropView where the user can adjust corners:
                        viewHolder.ivFullImage.SetOnClickListener(this);
                    }
                }

                if (croppedImagePath[position] != null)
                {
                    File croppedImgFile = new File(croppedImagePath[position]);
                    if (croppedImgFile.Exists())
                    {
                        // create bitmap in ARGB-format from cropped image file:
                        Bitmap croppedBitmap         = BitmapFactory.DecodeFile(croppedImgFile.AbsolutePath);
                        Bitmap drawableCroppedBitmap = croppedBitmap.Copy(Bitmap.Config.Argb8888, true);

                        // display the cropped image:
                        viewHolder.ivCroppedImage.SetImageBitmap(drawableCroppedBitmap);

                        // display the size (height and width) of the cropped image:
                        viewHolder.tvSizeCroppedImage.SetText(getPictureResolution(parent.Context, croppedImagePath[position]), TextView.BufferType.Normal);

                        // if a full image exists and user clicks on cropped image: call cropView where the user can adjust corners:
                        if (fullImgFile != null)
                        {
                            if (fullImgFile.Exists())
                            {
                                viewHolder.ivCroppedImage.SetOnClickListener(this);
                            }
                        }
                    }
                }
                return(convertView);
            }
예제 #57
0
 private void Init()
 {
     _borderPaint = new Paint();
     _colorPaint  = new Paint();
     _density     = Context.Resources.DisplayMetrics.Density;
 }
예제 #58
0
        private void AddBrushPaint(Paint paint, BaseBrush brush, Rect frame)
        {
            paint.SetStyle(Paint.Style.Fill);

            var sb = brush as SolidBrush;

            if (sb != null)
            {
                paint.SetARGB(sb.Color.A, sb.Color.R, sb.Color.G, sb.Color.B);
                return;
            }

            var lgb = brush as LinearGradientBrush;

            if (lgb != null)
            {
                var n = lgb.Stops.Count;
                if (n >= 2)
                {
                    var locs  = new float[n];
                    var comps = new int[n];
                    for (var i = 0; i < n; i++)
                    {
                        var s = lgb.Stops[i];
                        locs[i]  = (float)s.Offset;
                        comps[i] = s.Color.Argb;
                    }
                    var p1 = lgb.Absolute ? lgb.Start : frame.Position + lgb.Start * frame.Size;
                    var p2 = lgb.Absolute ? lgb.End : frame.Position + lgb.End * frame.Size;
                    var lg = new LinearGradient(
                        (float)p1.X, (float)p1.Y,
                        (float)p2.X, (float)p2.Y,
                        comps,
                        locs,
                        Shader.TileMode.Clamp);
                    paint.SetShader(lg);
                }
                return;
            }

            var rgb = brush as RadialGradientBrush;

            if (rgb != null)
            {
                var n = rgb.Stops.Count;
                if (n >= 2)
                {
                    var locs  = new float[n];
                    var comps = new int[n];
                    for (var i = 0; i < n; i++)
                    {
                        var s = rgb.Stops[i];
                        locs[i]  = (float)s.Offset;
                        comps[i] = s.Color.Argb;
                    }
                    var p1 = rgb.GetAbsoluteCenter(frame);
                    var r  = rgb.GetAbsoluteRadius(frame);
                    var rg = new RadialGradient(
                        (float)p1.X, (float)p1.Y,
                        (float)r.Max,
                        comps,
                        locs,
                        Shader.TileMode.Clamp);

                    paint.SetShader(rg);
                }
                return;
            }

            throw new NotSupportedException("Brush " + brush);
        }
예제 #59
0
        public override void ClearGradient(Paint paint, int width, int height)
        {
            InvalidateArrays();

            paint.SetShader(null);
        }
예제 #60
0
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            var boxView = (RoundedStackLayout)Element;

            double sourceWidth  = canvas.Width;
            double sourceHeight = canvas.Height;

            double desiredWidth  = sourceWidth;
            double desiredHeight = sourceHeight;

            var topLeftCornerSize     = _context.ToPixels(boxView.CornerRadius);
            var topRightCornerSize    = _context.ToPixels(boxView.CornerRadius);
            var bottomLeftCornerSize  = _context.ToPixels(boxView.CornerRadius);
            var bottomRightCornerSize = _context.ToPixels(boxView.CornerRadius);

            using (Paint paint = new Paint())
                using (Matrix matrix = new Matrix())
                    using (var path = new Path())
                    {
                        // TopLeft
                        if (boxView.CornersAttributes.HasFlag(CornerAttributes.TopLeftRounded))
                        {
                            path.MoveTo(0, (float)topLeftCornerSize);
                            path.QuadTo(0, 0, (float)topLeftCornerSize, 0);
                        }
                        else
                        {
                            path.MoveTo(0, 0);
                        }

                        // TopRight
                        if (boxView.CornersAttributes.HasFlag(CornerAttributes.TopRightRounded))
                        {
                            path.LineTo((float)(desiredWidth - topRightCornerSize), 0);
                            path.QuadTo((float)desiredWidth, 0, (float)desiredWidth, (float)topRightCornerSize);
                        }
                        else
                        {
                            path.LineTo((float)desiredWidth, 0);
                        }

                        // BottomRight
                        if (boxView.CornersAttributes.HasFlag(CornerAttributes.BottomRightRounded))
                        {
                            path.LineTo((float)desiredWidth, (float)(desiredHeight - bottomRightCornerSize));
                            path.QuadTo((float)desiredWidth, (float)desiredHeight, (float)(desiredWidth - bottomRightCornerSize), (float)desiredHeight);
                        }
                        else
                        {
                            path.LineTo((float)desiredWidth, (float)desiredHeight);
                        }

                        // BottomLeft
                        if (boxView.CornersAttributes.HasFlag(CornerAttributes.BottomLeftRounded))
                        {
                            path.LineTo((float)bottomLeftCornerSize, (float)desiredHeight);
                            path.QuadTo(0, (float)desiredHeight, 0, (float)(desiredHeight - bottomLeftCornerSize));
                        }
                        else
                        {
                            path.LineTo(0, (float)desiredHeight);
                        }

                        paint.Color = boxView.BackgroundColor.ToAndroid();

                        path.Close();
                        canvas.DrawPath(path, paint);
                    }
        }