Exemple #1
0
        /// <summary>
        /// Sets the value of ImageView.ImageMatrix based on Stretch.
        /// </summary>
        /// <param name="frameSize">In logical pixels</param>
        private void UpdateMatrix(Windows.Foundation.Size frameSize)
        {
            SetScaleType(ScaleType.Matrix);

            if (SourceImageSize.Width == 0 || SourceImageSize.Height == 0 || frameSize.Width == 0 || frameSize.Height == 0)
            {
                return;
            }

            var sourceRect = new Windows.Foundation.Rect(Windows.Foundation.Point.Zero, SourceImageSize);
            var imageRect  = new Windows.Foundation.Rect(Windows.Foundation.Point.Zero, frameSize);

            MeasureSource(imageRect, ref sourceRect);
            ArrangeSource(imageRect, ref sourceRect);

            var scaleX     = (sourceRect.Width / SourceImageSize.Width) * _sourceImageScale;
            var scaleY     = (sourceRect.Height / SourceImageSize.Height) * _sourceImageScale;
            var translateX = ViewHelper.LogicalToPhysicalPixels(sourceRect.X);
            var translateY = ViewHelper.LogicalToPhysicalPixels(sourceRect.Y);

            var matrix = new Android.Graphics.Matrix();

            matrix.PostScale((float)scaleX, (float)scaleY);
            matrix.PostTranslate(translateX, translateY);
            ImageMatrix = matrix;
        }
Exemple #2
0
        public void Invert()
        {
            var inverse = new ag.Matrix();

            this.Control.Invert(inverse);
            this.control = inverse;
        }
Exemple #3
0
        private protected void Render(
            Android.Graphics.Path path,
            Windows.Foundation.Size?size = null,
            double scaleX        = 1d,
            double scaleY        = 1d,
            double renderOriginX = 0d,
            double renderOriginY = 0d)
        {
            _path = path;
            if (_path == null)
            {
                return;
            }

            var matrix = new Android.Graphics.Matrix();

            matrix.SetScale((float)scaleX * (float)ViewHelper.Scale, (float)scaleY * (float)ViewHelper.Scale);
            matrix.PostTranslate(ViewHelper.LogicalToPhysicalPixels(renderOriginX), ViewHelper.LogicalToPhysicalPixels(renderOriginY));

            _path.Transform(matrix);

            _drawArea = GetPathBoundingBox(_path);

            _drawArea.Width  = size?.Width ?? _drawArea.Width;
            _drawArea.Height = size?.Height ?? _drawArea.Height;

            Invalidate();
        }
Exemple #4
0
        /// <summary>
        /// Sets the value of ImageView.ImageMatrix based on Stretch.
        /// </summary>
        /// <param name="frameSize">In logical pixels</param>
        private void UpdateMatrix(Windows.Foundation.Size frameSize)
        {
            SetScaleType(ScaleType.Matrix);

            if (SourceImageSize.Width == 0 || SourceImageSize.Height == 0 || frameSize.Width == 0 || frameSize.Height == 0)
            {
                return;
            }

            // Calculate the resulting space required on screen for the image
            var containerSize = this.MeasureSource(frameSize, SourceImageSize);

            // Calculate the position of the image to follow stretch and alignment requirements
            var sourceRect = this.ArrangeSource(frameSize, containerSize);

            var scaleX     = (sourceRect.Width / SourceImageSize.Width) * _sourceImageScale;
            var scaleY     = (sourceRect.Height / SourceImageSize.Height) * _sourceImageScale;
            var translateX = ViewHelper.LogicalToPhysicalPixels(sourceRect.X);
            var translateY = ViewHelper.LogicalToPhysicalPixels(sourceRect.Y);

            var matrix = new Android.Graphics.Matrix();

            matrix.PostScale((float)scaleX, (float)scaleY);
            matrix.PostTranslate(translateX, translateY);
            ImageMatrix = matrix;
        }
        public IndicatorLayout(Context context, Mode mode)

            : base(context)
        {
            //super(context);
            mArrowImageView = new ImageView(context);

            Drawable arrowD = Resources.GetDrawable(Resource.Drawable.indicator_arrow);
            mArrowImageView.SetImageDrawable(arrowD);

            int padding = Resources.GetDimensionPixelSize(Resource.Dimension.indicator_internal_padding);
            mArrowImageView.SetPadding(padding, padding, padding, padding);
            AddView(mArrowImageView);

            int inAnimResId, outAnimResId;
            switch (mode)
            {
                case Mode.PULL_FROM_END:
                    inAnimResId = Resource.Animation.slide_in_from_bottom;
                    outAnimResId = Resource.Animation.slide_out_to_bottom;
                    SetBackgroundResource(Resource.Drawable.indicator_bg_bottom);

                    // Rotate Arrow so it's pointing the correct way
                    mArrowImageView.SetScaleType(Android.Widget.ImageView.ScaleType.Matrix);
                    Matrix matrix = new Matrix();

                    matrix.SetRotate(180f, arrowD.IntrinsicWidth / 2f, arrowD.IntrinsicHeight / 2f);
                    mArrowImageView.ImageMatrix = matrix;
                    break;
                default:
                case Mode.PULL_FROM_START:
                    inAnimResId = Resource.Animation.slide_in_from_top;
                    outAnimResId = Resource.Animation.slide_out_to_top;
                    SetBackgroundResource(Resource.Drawable.indicator_bg_top);
                    break;
            }

            mInAnim = AnimationUtils.LoadAnimation(context, inAnimResId);
            mInAnim.SetAnimationListener(this);

            mOutAnim = AnimationUtils.LoadAnimation(context, outAnimResId);
            mOutAnim.SetAnimationListener(this);

            IInterpolator interpolator = new LinearInterpolator();

            //mRotateAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
            mRotateAnimation = new RotateAnimation(0, -180, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f);


            mRotateAnimation.Interpolator = interpolator;
            mRotateAnimation.Duration = DEFAULT_ROTATION_ANIMATION_DURATION;
            mRotateAnimation.FillAfter = true;

            mResetRotateAnimation = new RotateAnimation(-180, 0, Dimension.RelativeToSelf, 0.5f,
                    Dimension.RelativeToSelf, 0.5f);
            mResetRotateAnimation.Interpolator = interpolator;
            mResetRotateAnimation.Duration = DEFAULT_ROTATION_ANIMATION_DURATION;
            mResetRotateAnimation.FillAfter = true;

        }
Exemple #6
0
		AMatrix CreateMatrix()
		{
			AMatrix matrix = new AMatrix();

			RectF drawableBounds = new RectF(_drawable.Bounds);
			float halfStrokeWidth = _drawable.Paint.StrokeWidth / 2;

			drawableBounds.Left += halfStrokeWidth;
			drawableBounds.Top += halfStrokeWidth;
			drawableBounds.Right -= halfStrokeWidth;
			drawableBounds.Bottom -= halfStrokeWidth;

			switch (_aspect)
			{
				case Stretch.None:
					break;
				case Stretch.Fill:
					matrix.SetRectToRect(_pathFillBounds, drawableBounds, AMatrix.ScaleToFit.Fill);
					break;
				case Stretch.Uniform:
					matrix.SetRectToRect(_pathFillBounds, drawableBounds, AMatrix.ScaleToFit.Center);
					break;
				case Stretch.UniformToFill:
					float widthScale = drawableBounds.Width() / _pathFillBounds.Width();
					float heightScale = drawableBounds.Height() / _pathFillBounds.Height();
					float maxScale = Math.Max(widthScale, heightScale);
					matrix.SetScale(maxScale, maxScale);
					matrix.PostTranslate(
						drawableBounds.Left - maxScale * _pathFillBounds.Left,
						drawableBounds.Top - maxScale * _pathFillBounds.Top);
					break;
			}

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

			double desiredWidth = sourceWidth;
			double desiredHeight = sourceHeight;

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

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

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

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

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

			if (cropX < 0)
				cropX = 0;

			if (cropY < 0)
				cropY = 0;

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

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

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

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

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

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

				return bitmap;				
			}
		}
Exemple #8
0
        // シャッターを切った時のコールバック
        public void OnPictureTaken(byte[] data, AndroidCamera camera)
        {
            try {
                var SaveDir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "Camera");
                if (!SaveDir.Exists())
                {
                    SaveDir.Mkdir();
                }


                // 非同期で画像の回転・保存・アルバムへの登録
                Task.Run(async() => {
                    // 保存ディレクトリに入ってるファイル数をカウント
                    var Files = SaveDir.List();
                    int count = 0;
                    foreach (var tmp in Files)
                    {
                        count++;
                    }

                    Matrix matrix = new Matrix();                       // 回転用の行列
                    matrix.SetRotate(90 - DetectScreenOrientation());
                    Bitmap original = BitmapFactory.DecodeByteArray(data, 0, data.Length);
                    Bitmap rotated  = Bitmap.CreateBitmap(original, 0, 0, original.Width, original.Height, matrix, true);

                    var FileName = new Java.IO.File(SaveDir, "DCIM_" + (count + 1) + ".jpg");


                    // ファイルをストレージに保存
                    FileStream stream = new FileStream(FileName.ToString(), FileMode.CreateNew);
                    await rotated.CompressAsync(Bitmap.CompressFormat.Jpeg, 90, stream);
                    stream.Close();

                    Android.Media.ExifInterface Exif = new ExifInterface(FileName.ToString());
                    Exif.SetAttribute(ExifInterface.TagGpsLatitude, Latitude);
                    Exif.SetAttribute(ExifInterface.TagGpsLongitude, Longitude);
                    Exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N");
                    Exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E");
                    Exif.SaveAttributes();


                    // 保存したファイルをアルバムに登録
                    string[] FilePath = { Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim) + "/Camera/" + "DCIM_" + (count + 1) + ".jpg" };
                    string[] mimeType = { "image/jpeg" };
                    MediaScannerConnection.ScanFile(ApplicationContext, FilePath, mimeType, null);
                    RunOnUiThread(() => {
                        Toast.MakeText(ApplicationContext, "保存しました\n" + FileName, ToastLength.Short).Show();
                    });
                    original.Recycle();
                    rotated.Recycle();

                    isTakeEnabled = false;
                });

                m_Camera.StartPreview();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Exemple #9
0
 public void Dispose()
 {
     if (control != null)
     {
         control.Dispose();
         control = null;
     }
 }
Exemple #10
0
        public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY)
        {
#if TODO
            var m = new ag.Matrix(scaleX, 0, 0, scaleY, centerX - centerX * scaleX, centerY - centerY * scaleY);
            this.Control.Multiply(m, ag.MatrixOrder.Prepend);
#else
            throw new NotImplementedException();
#endif
        }
Exemple #11
0
        public void Skew(float skewX, float skewY)
        {
#if TODO
            var m = new ag.Matrix(1, (float)Math.Tan(Conversions.DegreesToRadians(skewX)), (float)Math.Tan(Conversions.DegreesToRadians(skewY)), 1, 0, 0);
            this.Control.Multiply(m, ag.MatrixOrder.Prepend);
#else
            throw new NotImplementedException();
#endif
        }
Exemple #12
0
 private Android.Graphics.Bitmap rotateMyBitmap(Android.Graphics.Bitmap bmp)
 {
     //*****旋转一下
     Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
     matrix.PostRotate(270);
     Android.Graphics.Bitmap nbmp2 = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true);
     bmp.Dispose();
     return(nbmp2);
 }
Exemple #13
0
        private static Bitmap ReverseBitmap(Bitmap src)
        {
            Android.Graphics.Matrix m = new Android.Graphics.Matrix();
            m.PreScale(1, -1);
            Bitmap dst = Bitmap.CreateBitmap(src, 0, 0, src.Width, src.Height, m, false);

            dst.Density = (int)Android.Util.DisplayMetricsDensity.Default;

            return(dst);
        }
Exemple #14
0
        internal override Android.Graphics.Matrix ToNativeTransform(Android.Graphics.Matrix targetMatrix = null, Size size = default(Size), bool isBrush = false)
        {
            if (targetMatrix == null)
            {
                targetMatrix = new Android.Graphics.Matrix();
            }

            targetMatrix.PostTranslate((float)X, (float)Y);

            return(targetMatrix);
        }
Exemple #15
0
        public void Create(float xx, float yx, float xy, float yy, float dx, float dy)
        {
            control = new ag.Matrix();
            var values = new float[]
            {
                xx, yx, 1,
                xy, yy, 1,
                dx, dy, 1
            };

            control.SetValues(values);
        }
        public static Bitmap CreateBitmap(Texture2D image, Vector2 scale, float rotation, Vector2 origin)
        {
            Matrix matrix = new Matrix();

            matrix.PostScale(scale.X, scale.Y);
            matrix.PostRotate(rotation, origin.X, origin.Y);

            Bitmap source    = Texture2D2Bitmap(image);
            Bitmap newBitmap = Bitmap.CreateBitmap(source, 0, 0, source.Width, source.Height, matrix, true);

            return(newBitmap);
        }
Exemple #17
0
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            ContentResolver cr = context_.ContentResolver;

            /** 画像をファイルパスから検索 */


            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            var    bitmap       = BitmapFactory.DecodeFile(image_[position]);
            int    imageHeight  = bitmap.Height;
            int    imageWidth   = bitmap.Width;
            String imageType    = options.OutMimeType;
            int    inSampleSize = 1;

            if (imageHeight > 320 || imageWidth > 240)
            {
                int halfHeight = imageHeight / 2;
                int halfWidth  = imageWidth / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) >= 320 &&
                       (halfWidth / inSampleSize) >= 240)
                {
                    inSampleSize *= 2;
                }
            }
            options.InSampleSize       = inSampleSize;
            options.InJustDecodeBounds = false;
            Android.Media.ExifInterface exif = new Android.Media.ExifInterface(image_[position]);
            //var orientation = int.Parse(exif.GetAttribute(Android.Media.ExifInterface.TagOrientation));
            var thumbnail = BitmapFactory.DecodeFile(image_[position], options);

            Android.Graphics.Matrix mat = new Android.Graphics.Matrix();


            if (thumbnail.Width > thumbnail.Height)
            {
                mat.SetRotate(90, thumbnail.Width / 2, thumbnail.Height / 2);
                mat.PreScale(320.0f / thumbnail.Width, 240.0f / thumbnail.Height);
            }
            else
            {
                mat.PreScale(240.0f / thumbnail.Width, 320.0f / thumbnail.Height);
            }
            thumbnail = Android.Graphics.Bitmap.CreateBitmap(thumbnail, 0, 0, thumbnail.Width, thumbnail.Height, mat, true);
            ((CameraViewHolder)holder).image_.SetImageBitmap(thumbnail);

            holder.ItemView.Click -= ItemView_Click;
            holder.ItemView.Click += ItemView_Click;
        }
        public static Matrix ToXwt(this AG.Matrix value)
        {
            var m = new float[9];

            value.GetValues(m);
            return(new Matrix(
                       m [AG.Matrix.MscaleX],
                       m [AG.Matrix.MskewY],
                       m [AG.Matrix.MskewX],
                       m [AG.Matrix.MscaleY],
                       m [AG.Matrix.MtransX],
                       m [AG.Matrix.MtransY]));
        }
        public static void SetValues(this AG.Matrix dest, Matrix m)
        {
            var v = new float[9];

            dest.GetValues(v);
            v [AG.Matrix.MtransX] = (float)m.OffsetX;
            v [AG.Matrix.MtransY] = (float)m.OffsetY;
            v [AG.Matrix.MskewX]  = (float)m.M21;
            v [AG.Matrix.MskewY]  = (float)m.M12;
            v [AG.Matrix.MscaleX] = (float)m.M11;
            v [AG.Matrix.MscaleY] = (float)m.M22;
            dest.SetValues(v);
        }
Exemple #20
0
        internal override Android.Graphics.Matrix ToNativeTransform(Android.Graphics.Matrix targetMatrix = null, Size size = default(Size), bool isBrush = false)
        {
            if (targetMatrix == null)
            {
                targetMatrix = new Android.Graphics.Matrix();
            }

            var pivot = this.GetPivot(size, isBrush);

            targetMatrix.PostSkew((float)AngleX, (float)AngleY, (float)pivot.X, (float)pivot.Y);

            return(targetMatrix);
        }
        protected internal override Shader GetShader(Size size)
        {
            if (GradientStops.Count == 0)
            {
                return(null);
            }

            var colors    = GradientStops.SelectToList(s => ((Android.Graphics.Color)GetColorWithOpacity(s.Color)).ToArgb());
            var locations = GradientStops.SelectToList(s => (float)s.Offset);

            if (GradientStops.Count == 1)
            {
                // Android LinearGradient requires two ore more stop points.
                // We work around this by duplicating the first gradient stop.
                colors.Add(colors[0]);
                locations.Add(locations[0]);
            }

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

            Android.Graphics.Matrix nativeTransformMatrix = null;
            if (RelativeTransform != null)
            {
                var matrix = RelativeTransform.ToMatrix(Point.Zero, new Size(width, height));
                matrix.M31           *= (float)width;
                matrix.M32           *= (float)height;
                nativeTransformMatrix = matrix.ToNative();
            }

            //Matrix .MapPoints takes an array of floats
            var pts = MappingMode == BrushMappingMode.RelativeToBoundingBox
                                ? new[]
            {
                (float)(StartPoint.X * width),
                (float)(StartPoint.Y * height),
                (float)(EndPoint.X * width),
                (float)(EndPoint.Y * height)
            }
                                : new[]
            {
                (float)ViewHelper.LogicalToPhysicalPixels(StartPoint.X),
                (float)ViewHelper.LogicalToPhysicalPixels(StartPoint.Y),
                (float)ViewHelper.LogicalToPhysicalPixels(EndPoint.X),
                (float)ViewHelper.LogicalToPhysicalPixels(EndPoint.Y)
            };

            nativeTransformMatrix?.MapPoints(pts);
            nativeTransformMatrix?.Dispose();
            return(new LinearGradient(pts[0], pts[1], pts[2], pts[3], colors.ToArray(), locations.ToArray(), Shader.TileMode.Clamp));
        }
Exemple #22
0
        public bool ReadFile(String fileName, Mat mat, CvEnum.ImreadModes loadType)
        {
            try
            {
                int rotation = 0;
                Android.Media.ExifInterface exif = new Android.Media.ExifInterface(fileName);
                int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue);
                switch (orientation)
                {
                case (int)Android.Media.Orientation.Rotate270:
                    rotation = 270;
                    break;

                case (int)Android.Media.Orientation.Rotate180:
                    rotation = 180;
                    break;

                case (int)Android.Media.Orientation.Rotate90:
                    rotation = 90;
                    break;
                }

                using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(fileName))
                {
                    if (rotation == 0)
                    {
                        bmp.ToMat(mat);
                    }
                    else
                    {
                        Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
                        matrix.PostRotate(rotation);
                        using (Android.Graphics.Bitmap rotated = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true))
                        {
                            //manually disposed sooner such that memory is released.
                            bmp.Dispose();
                            rotated.ToMat(mat);
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                //throw;
                return(false);
            }
        }
Exemple #23
0
        /// <summary>
        /// Create matrix to transform image based on relative dimensions of bitmap and drawRect, Stretch mode, and RelativeTransform
        /// </summary>
        /// <param name="drawRect"></param>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private Android.Graphics.Matrix GenerateMatrix(Windows.Foundation.Rect drawRect, Bitmap bitmap)
        {
            var matrix = new Android.Graphics.Matrix();

            // Note that bitmap.Width and bitmap.Height (in physical pixels) are automatically scaled up when loaded from local resources, but aren't when acquired externally.
            // This means that bitmaps acquired externally might not render the same way on devices with different densities when using Stretch.None.

            var sourceRect      = new Windows.Foundation.Rect(0, 0, bitmap.Width, bitmap.Height);
            var destinationRect = GetArrangedImageRect(sourceRect.Size, drawRect);

            matrix.SetRectToRect(sourceRect.ToRectF(), destinationRect.ToRectF(), Android.Graphics.Matrix.ScaleToFit.Fill);

            RelativeTransform?.ToNative(matrix, new Size(drawRect.Width, drawRect.Height), isBrush: true);
            return(matrix);
        }
Exemple #24
0
        private Bitmap GetPlaneBitmap(int id)
        {
            TextView view = (TextView)mActivity.FindViewById(id);

            view.DrawingCacheEnabled = true;
            view.Measure(View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified),
                         View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));
            view.Layout(0, 0, view.MeasuredWidth, view.MeasuredHeight);
            Bitmap bitmap = view.DrawingCache;

            Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
            matrix.SetScale(MATRIX_SCALE_SX, MATRIX_SCALE_SY);
            if (bitmap != null)
            {
                bitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
            }
            return(bitmap);
        }
Exemple #25
0
        public static Bitmap GetAndRotateBitmap(string fileName)
        {
            Bitmap bitmap = BitmapFactory.DecodeFile(fileName);

            // Images are being saved in landscape, so rotate them back to portrait if they were taken in portrait
            // See https://forums.xamarin.com/discussion/5409/photo-being-saved-in-landscape-not-portrait
            // See http://developer.android.com/reference/android/media/ExifInterface.html
            using (Matrix mtx = new Matrix())
            {
                if (Android.OS.Build.Product.Contains("Emulator"))
                {
                    mtx.PreRotate(90);
                }
                else
                {
                    ExifInterface exif = new ExifInterface(fileName);
                    var orientation = (Orientation)exif.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Normal);

                    //TODO : handle FlipHorizontal, FlipVertical, Transpose and Transverse
                    switch (orientation)
                    {
                        case Orientation.Rotate90:
                            mtx.PreRotate(90);
                            break;
                        case Orientation.Rotate180:
                            mtx.PreRotate(180);
                            break;
                        case Orientation.Rotate270:
                            mtx.PreRotate(270);
                            break;
                        case Orientation.Normal:
                            // Normal, do nothing
                            break;
                        default:
                            break;
                    }
                }

                if (mtx != null)
                    bitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, mtx, false);
            }

            return bitmap;
        }
Exemple #26
0
        public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight)
        {
            int width  = bm.Width;
            int height = bm.Height;

            newHeight = CalculateProportionalHeight(bm.Width, bm.Height, newWidth);

            float scaleWidth  = ((float)newWidth) / width;
            float scaleHeight = ((float)newHeight) / height;
            var   matrix      = new Matrix1();

            matrix.PostScale(scaleWidth, scaleHeight);

            Bitmap resizedBitmap = Bitmap.CreateBitmap(
                bm, 0, 0, width, height, matrix, false);

            bm.Recycle();
            return(resizedBitmap);
        }
Exemple #27
0
        internal override Android.Graphics.Matrix ToNativeTransform(Android.Graphics.Matrix targetMatrix = null, Windows.Foundation.Size size = default(Windows.Foundation.Size), bool isBrush = false)
        {
            if (targetMatrix == null)
            {
                targetMatrix = new Android.Graphics.Matrix();
            }

            var pivot = this.GetPivot(size, isBrush);

            //Apply transformations in order
            targetMatrix.PostScale((float)ScaleX, (float)ScaleY, (float)pivot.X, (float)pivot.Y);

            targetMatrix.PostSkew((float)SkewX, (float)SkewY, (float)pivot.X, (float)pivot.Y);

            targetMatrix.PostRotate((float)Rotation, (float)pivot.X, (float)pivot.Y);

            targetMatrix.PostTranslate((float)TranslateX, (float)TranslateY);

            return(targetMatrix);
        }
    protected Bitmap resizeImage(int w, int h)
    {
        // load the origial Bitmap
        Android.Graphics.Bitmap BitmapOrg = null;

        BitmapOrg = ((BitmapDrawable)this.Drawable).Bitmap.Copy(Bitmap.Config.Argb8888, true);

        int width     = BitmapOrg.Width;
        int height    = BitmapOrg.Height;
        int newWidth  = w;
        int newHeight = h;

        float scaleWidth  = ((float)newWidth) / width;
        float scaleHeight = ((float)newHeight) / height;

        Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
        matrix.PostScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Android.Graphics.Bitmap.CreateBitmap(BitmapOrg, 0, 0, width, height, matrix, true);

        return(resizedBitmap);
    }
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            if (_path == null)
            {
                return;
            }

            AMatrix transformMatrix = CreateMatrix();

            _path.Transform(transformMatrix);
            transformMatrix.MapRect(_pathFillBounds);
            transformMatrix.MapRect(_pathStrokeBounds);

            if (_fill != null)
            {
                _drawable.Paint.SetStyle(Paint.Style.Fill);
                _drawable.Paint.Color = _fill;
                _drawable.Draw(canvas);
                _drawable.Paint.SetShader(null);
            }

            if (_stroke != null)
            {
                _drawable.Paint.SetStyle(Paint.Style.Stroke);
                _drawable.Paint.Color = _stroke;
                _drawable.Draw(canvas);
                _drawable.Paint.SetShader(null);
            }

            AMatrix inverseTransformMatrix = new AMatrix();

            transformMatrix.Invert(inverseTransformMatrix);
            _path.Transform(inverseTransformMatrix);
            inverseTransformMatrix.MapRect(_pathFillBounds);
            inverseTransformMatrix.MapRect(_pathStrokeBounds);
        }
        droidGraphics.Matrix ComputeStretchMatrix()
        {
            droidGraphics.Matrix matrix = new droidGraphics.Matrix();

            // Get the drawable bounds decreased by stroke thickness
            droidGraphics.RectF drawableBounds = new droidGraphics.RectF(drawable.Bounds);
            float halfStrokeWidth = drawable.Paint.StrokeWidth / 2;

            drawableBounds.Left   += halfStrokeWidth;
            drawableBounds.Top    += halfStrokeWidth;
            drawableBounds.Right  -= halfStrokeWidth;
            drawableBounds.Bottom -= halfStrokeWidth;

            switch (stretch)
            {
            case Stretch.None:
                break;

            case Stretch.Fill:
                matrix.SetRectToRect(pathFillBounds, drawableBounds, droidGraphics.Matrix.ScaleToFit.Fill);
                break;

            case Stretch.Uniform:
                matrix.SetRectToRect(pathFillBounds, drawableBounds, droidGraphics.Matrix.ScaleToFit.Center);
                break;

            case Stretch.UniformToFill:
                float widthScale  = drawableBounds.Width() / pathFillBounds.Width();
                float heightScale = drawableBounds.Height() / pathFillBounds.Height();
                float maxScale    = Math.Max(widthScale, heightScale);

                matrix.SetScale(maxScale, maxScale);
                matrix.PostTranslate(drawableBounds.Left - maxScale * pathFillBounds.Left,
                                     drawableBounds.Top - maxScale * pathFillBounds.Top);
                break;
            }
            return(matrix);
        }
        private IDisposable BuildDrawableLayer()
        {
            if (_controlHeight == 0 || _controlWidth == 0)
            {
                return(Disposable.Empty);
            }

            var drawables = new List <Drawable>();

            var path = GetPath();

            if (path == null)
            {
                return(Disposable.Empty);
            }

            // Scale the path using its Stretch
            Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
            switch (this.Stretch)
            {
            case Media.Stretch.Fill:
            case Media.Stretch.None:
                matrix.SetScale((float)_scaleX, (float)_scaleY);
                break;

            case Media.Stretch.Uniform:
                var scale = Math.Min(_scaleX, _scaleY);
                matrix.SetScale((float)scale, (float)scale);
                break;

            case Media.Stretch.UniformToFill:
                scale = Math.Max(_scaleX, _scaleY);
                matrix.SetScale((float)scale, (float)scale);
                break;
            }
            path.Transform(matrix);

            // Move the path using its alignements
            var translation = new Android.Graphics.Matrix();

            var pathBounds = new RectF();

            // Compute the bounds. This is needed for stretched shapes and stroke thickness translation calculations.
            path.ComputeBounds(pathBounds, true);

            if (Stretch == Stretch.None)
            {
                // Since we are not stretching, ensure we are using (0, 0) as origin.
                pathBounds.Left = 0;
                pathBounds.Top  = 0;
            }

            if (!ShouldPreserveOrigin)
            {
                //We need to translate the shape to take in account the stroke thickness
                translation.SetTranslate((float)(-pathBounds.Left + PhysicalStrokeThickness * 0.5f), (float)(-pathBounds.Top + PhysicalStrokeThickness * 0.5f));
            }

            path.Transform(translation);

            // Draw the fill
            var drawArea = new Foundation.Rect(0, 0, _controlWidth, _controlHeight);

            var imageBrushFill = Fill as ImageBrush;

            if (imageBrushFill != null)
            {
                var bitmapDrawable = new BitmapDrawable(Context.Resources, imageBrushFill.TryGetBitmap(drawArea, () => RefreshShape(forceRefresh: true), path));
                drawables.Add(bitmapDrawable);
            }
            else
            {
                var fill      = Fill ?? SolidColorBrushHelper.Transparent;
                var fillPaint = fill.GetFillPaint(drawArea);

                var lineDrawable = new PaintDrawable();
                lineDrawable.Shape       = new PathShape(path, (float)_controlWidth, (float)_controlHeight);
                lineDrawable.Paint.Color = fillPaint.Color;
                lineDrawable.Paint.SetShader(fillPaint.Shader);
                lineDrawable.Paint.SetStyle(Paint.Style.Fill);
                lineDrawable.Paint.Alpha = fillPaint.Alpha;

                this.SetStrokeDashEffect(lineDrawable.Paint);

                drawables.Add(lineDrawable);
            }

            // Draw the contour
            if (Stroke != null)
            {
                using (var strokeBrush = new Paint(Stroke.GetStrokePaint(drawArea)))
                {
                    var lineDrawable = new PaintDrawable();
                    lineDrawable.Shape       = new PathShape(path, (float)_controlWidth, (float)_controlHeight);
                    lineDrawable.Paint.Color = strokeBrush.Color;
                    lineDrawable.Paint.SetShader(strokeBrush.Shader);
                    lineDrawable.Paint.StrokeWidth = (float)PhysicalStrokeThickness;
                    lineDrawable.Paint.SetStyle(Paint.Style.Stroke);
                    lineDrawable.Paint.Alpha = strokeBrush.Alpha;

                    this.SetStrokeDashEffect(lineDrawable.Paint);

                    drawables.Add(lineDrawable);
                }
            }

            var layerDrawable = new LayerDrawable(drawables.ToArray());

            // Set bounds must always be called, otherwise the android layout engine can't determine
            // the rendering size. See Drawable documentation for details.
            layerDrawable.SetBounds(0, 0, (int)_controlWidth, (int)_controlHeight);

            return(SetOverlay(this, layerDrawable));
        }
 public static void Prepend(this AG.Matrix dest, Matrix m)
 {
     dest.PreTranslate((float)m.OffsetX, (float)m.OffsetY);
     dest.PreScale((float)m.M11, (float)m.M22);
     dest.PreSkew((float)m.M21, (float)m.M12);
 }
 public void SetMatrix(Matrix matrix)
 {
     this.matrix = matrix;
     InvalidateSelf();
 }
Exemple #34
0
		public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY)
		{
#if TODO
			var m = new ag.Matrix(scaleX, 0, 0, scaleY, centerX - centerX * scaleX, centerY - centerY * scaleY);
			this.Control.Multiply(m, ag.MatrixOrder.Prepend);
#else
			throw new NotImplementedException();
#endif
		}
        /// <summary>
        /// Helper method to provide the corresponding Icon for a station
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public BitmapDescriptor CreateStationIcon(Station station)
        {
            Bitmap bitmap = null;
            var value = _settingsService.Settings.IsBikeMode ? station.AvailableBikes : station.AvailableBikeStands;
            var printedValue = value.HasValue ? value.Value.ToString() : string.Empty;
            if (!station.Loaded)
            {
                printedValue = string.Empty;
                bitmap = _iconGreyLowAlpha;
                bitmap = bitmap.Copy(bitmap.GetConfig(), true);
            }
            else if (station.Status == false)
            {
                printedValue = "!";
                bitmap = _iconGrey;
                bitmap = bitmap.Copy(bitmap.GetConfig(), true);
            }
            else if (station.ImageAvailable != null || station.ImageDocks != null)
            {
                if (_metrics == null)
                {
                    _metrics = new DisplayMetrics();
                    (CrossCurrentActivity.Current.Activity as MainActivity).WindowManager.DefaultDisplay.GetMetrics(_metrics);
                }

                bitmap = _iconGrey;
                bitmap = bitmap.Copy(bitmap.GetConfig(), true);
                try
                {
                    var data = (byte[])(_settingsService.Settings.IsBikeMode ? station.ImageAvailable : station.ImageDocks);
                    var gifDecoder = new GifDecoder();
                    gifDecoder.read(data);
                    if (gifDecoder.getFrameCount() != 0)
                    {
                        gifDecoder.advance();
                        var bmp = gifDecoder.getNextFrame();
                        var canvas = new Canvas(bitmap);

                        int width = bmp.Width;
                        int height = bmp.Height;
                        float scaleWidth = _metrics.ScaledDensity;
                        float scaleHeight = _metrics.ScaledDensity;
                        // create a matrix for the scaling manipulation
                        Matrix matrix = new Matrix();
                        // resize the bitmap
                        matrix.PostScale(scaleWidth, scaleHeight);

                        // recreate the new Bitmap
                        var resizedBitmap = Bitmap.CreateBitmap(bmp, 0, 0, width, height, matrix, true);

                        int xPos = canvas.Width / 2 - resizedBitmap.Width / 2;
                        int yPos = canvas.Height / 2 - resizedBitmap.Height;
                        canvas.DrawBitmap(resizedBitmap, xPos, yPos, null);
                    }

                }
                catch (System.Exception e)
                {
                }

            }
            else {
                if (value == 0)
                {
                    bitmap = _iconRed;
                }
                else if (value < 5)
                {
                    bitmap = _iconOrange;
                }
                else if (value >= 5)
                {
                    bitmap = _iconGreen;
                }
                else
                {
                    printedValue = "?";
                    bitmap = _iconGrey;
                }
            }

            if (printedValue != string.Empty)
            {
                bitmap = bitmap.Copy(bitmap.GetConfig(), true);
                Canvas canvas = new Canvas(bitmap);
                int xPos = (canvas.Width / 2);
                int yPos = (int)((canvas.Height / 2) - ((_textPaint.Descent() + _textPaint.Ascent()) / 2));
                canvas.DrawText(printedValue, xPos + 1, yPos - LayoutHelper.ConvertDpToPixel(6), _textPaint);
            }

            var icon = BitmapDescriptorFactory.FromBitmap(bitmap);
            bitmap.Recycle();
            return icon;
        }
Exemple #36
0
		public void Create()
		{
			control = new ag.Matrix();
		}
Exemple #37
0
		public void Skew(float skewX, float skewY)
		{
#if TODO
			var m = new ag.Matrix(1, (float)Math.Tan(Conversions.DegreesToRadians(skewX)), (float)Math.Tan(Conversions.DegreesToRadians(skewY)), 1, 0, 0);
			this.Control.Multiply(m, ag.MatrixOrder.Prepend);
#else
			throw new NotImplementedException();
#endif
		}
Exemple #38
0
		public void Create(float xx, float yx, float xy, float yy, float dx, float dy)
		{
			control = new ag.Matrix();
			var values = new float[]
			{
				xx, yx, 1,
				xy, yy, 1,
				dx, dy, 1
			};
			control.SetValues(values);
		}
Exemple #39
0
 public void UpdateShapeTransform(AMatrix matrix)
 {
     _transform = matrix;
     _path.Transform(_transform);
     Invalidate();
 }
Exemple #40
0
		public void Dispose()
		{
			if (control != null)
			{
				control.Dispose();
				control = null;
			}
		}
Exemple #41
0
		public void Invert()
		{
			var inverse = new ag.Matrix();
			this.Control.Invert(inverse);
			this.control = inverse;
		}
Exemple #42
0
		public MatrixHandler(ag.Matrix matrix)
		{
			control = matrix;
		}
        //@Override
        protected override void OnSizeChanged(int width, int height, int oldw, int oldh)
        {

            int centerX = width / 2;
            int centerY = height / 2;

            innerPadding = (int)(paramInnerPadding * width / 100);
            outerPadding = (int)(paramOuterPadding * width / 100);
            arrowPointerSize = (int)(paramArrowPointerSize * width / 100);
            valueSliderWidth = (int)(paramValueSliderWidth * width / 100);

            outerWheelRadius = width / 2 - outerPadding - arrowPointerSize;
            innerWheelRadius = outerWheelRadius - valueSliderWidth;
            colorWheelRadius = innerWheelRadius - innerPadding;

            outerWheelRect.Set(centerX - outerWheelRadius, centerY - outerWheelRadius, centerX + outerWheelRadius, centerY + outerWheelRadius);
            innerWheelRect.Set(centerX - innerWheelRadius, centerY - innerWheelRadius, centerX + innerWheelRadius, centerY + innerWheelRadius);

            colorWheelBitmap = createColorWheelBitmap(colorWheelRadius * 2, colorWheelRadius * 2);

            gradientRotationMatrix = new Matrix();
            gradientRotationMatrix.PreRotate(270, width / 2, height / 2);

            colorViewPath.ArcTo(outerWheelRect, 270, -180);
            colorViewPath.ArcTo(innerWheelRect, 90, 180);

            valueSliderPath.ArcTo(outerWheelRect, 270, 180);
            valueSliderPath.ArcTo(innerWheelRect, 90, -180);

        }
	protected Bitmap resizeImage(int w, int h)
	{
		// load the origial Bitmap
		Android.Graphics.Bitmap BitmapOrg = null;

		BitmapOrg = ((BitmapDrawable)this.Drawable).Bitmap.Copy (Bitmap.Config.Argb8888, true);

		int width = BitmapOrg.Width;
		int height = BitmapOrg.Height;
		int newWidth = w;
		int newHeight = h;
		
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
		matrix.PostScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Android.Graphics.Bitmap.CreateBitmap(BitmapOrg, 0, 0, width, height, matrix, true);
		return resizedBitmap;
	}
		private void Init() {
			this.SetScaleType (SCALE_TYPE);
			mReady = true;

			mDrawableRect = new RectF ();
			mBorderRect = new RectF ();

			mShaderMatrix = new Matrix ();
			mBitmapPaint = new Paint ();
			mBorderPaint = new Paint ();

			if (mSetupPending) {
				setup();
				mSetupPending = false;
			}
		}
Exemple #46
0
        public void DrawShowcase(Canvas canvas, float x, float y, float scaleMultiplier, float radius)
        {
            Matrix mm = new Matrix();
            mm.PostScale(scaleMultiplier, scaleMultiplier, x, y);
            canvas.Matrix = mm;

            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb)
            {
                canvas.DrawCircle(x, y, radius, mEraser);
            }

            mShowcaseDrawable.SetBounds(mShowcaseRect.Left, mShowcaseRect.Top, mShowcaseRect.Right, mShowcaseRect.Bottom);
            mShowcaseDrawable.Draw(canvas);

            canvas.Matrix = new Matrix();
        }