Example #1
0
 public Border(double width, LineStyle style, Color color, Xamarin.Forms.Size radius)
 {
     LeftWidth  = TopWidth = RightWidth = BottomWidth = width;
     LeftStyle  = TopStyle = RightStyle = BottomStyle = style;
     LeftColor  = TopColor = RightColor = BottomColor = color;
     BottomLeft = BottomRight = TopLeft = TopRight = radius;
 }
Example #2
0
        protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
        {
            using (var h = new Handler(Looper.MainLooper))
            {
                h.Post(() =>
                {
                    double width  = base.Context.FromPixels((double)(right - left));
                    double height = base.Context.FromPixels((double)(bottom - top));
                    var size      = new Xamarin.Forms.Size(width, height);

                    var msw = MeasureSpec.MakeMeasureSpec(right - left, MeasureSpecMode.Exactly);
                    var msh = MeasureSpec.MakeMeasureSpec(bottom - top, MeasureSpecMode.Exactly);
                    _nativeView.Measure(msw, msh);
                    _nativeView.Layout(0, 0, right - left, bottom - top);

                    if (size != _previousSize || !_isLaidOut)
                    {
                        var layout = _viewCell.View as Layout <Xamarin.Forms.View>;

                        if (layout != null)
                        {
                            layout.Layout(new Rectangle(0, 0, width, height));
                            layout.ForceLayout();
                            FixChildLayouts(layout);
                            _isLaidOut = true;
                        }
                    }

                    _previousSize = size;
                });
            }
        }
Example #3
0
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            //var selector = Element.ItemTemplate as DataTemplateSelector;
            //if (selector != null)
            //{
            //    selector.SelectTemplate(item, _listView);
            //}

            var gridViewCell = viewType == 0 ?
                               Element.ItemTemplate.CreateContent() as Plugin.GridViewControl.Common.FastGridCell :
                               Element.GroupHeaderTemplate.CreateContent() as Plugin.GridViewControl.Common.FastGridCell;

            // reflection method of setting isplatformenabled property
            // We are going to re-set the Platform here because in some cases (headers mostly) its possible this is unset and
            // when the binding context gets updated the measure passes will all fail. By applying this here the Update call
            // further down will result in correct layouts.
            var p = PlatformProperty.GetValue(Element);

            PlatformProperty.SetValue(gridViewCell, p);

            var initialCellSize = new Xamarin.Forms.Size(Element.MinItemWidth, Element.RowHeight);
            var view            = new GridViewCellContainer(parent.Context, gridViewCell, parent, initialCellSize);

            //Only add the click handler for items (not group headers.)
            if (viewType == 0)
            {
                view.Click += MMainView_Click;
            }

            //Height of the view will be taken as RowHeight for child items
            //and the heightrequest property of the first view in the template
            //or the render height (whatever that is) if the heightrequest property is not defined.
            var height = viewType == 0 ? Convert.ToInt32(Element.RowHeight) :
                         gridViewCell.View.HeightRequest != -1 ?
                         Convert.ToInt32(gridViewCell.View.HeightRequest) :
                         Convert.ToInt32(gridViewCell.RenderHeight);

            var width = Convert.ToInt32(Element.MinItemWidth);
            var dpW   = ConvertDpToPixels(width);
            var dpH   = ConvertDpToPixels(height);

            //If there are no minimums then the view doesn't render at all.
            view.SetMinimumWidth(dpW);
            view.SetMinimumHeight(dpH);

            var d = parent.Context.GetDrawable("statelist_item_background.xml");

            view.SetBackground(d);

            //If not set to match parent then the view doesn't stretch to fill.
            //This is not necessary anymore with the plaform fix above.
            //view.LayoutParameters = new GridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);

            //Wrap the view.
            view.SetOnLongClickListener(this);
            GridViewCell myView = new GridViewCell(view);

            //return the view.
            return(myView);
        }
        private Xamarin.Forms.Size GetSize(int imageWidth, int imageHeight, int maxWidth, int maxHeight)
        {
            Xamarin.Forms.Size size;
            if (maxHeight > 0 && maxWidth > 0 && imageWidth > maxWidth && imageHeight > maxHeight)
            {
                float ratioBitmap = (float)imageWidth / (float)imageHeight;
                float ratioMax    = (float)maxWidth / (float)maxHeight;

                int finalWidth  = maxWidth;
                int finalHeight = maxHeight;
                if (ratioMax > 1)
                {
                    finalWidth = (int)((float)maxHeight * ratioBitmap);
                }
                else
                {
                    finalHeight = (int)((float)maxWidth / ratioBitmap);
                }

                size = new Xamarin.Forms.Size(finalWidth, finalHeight);
            }
            else
            {
                size = new Xamarin.Forms.Size(imageWidth, imageHeight);
            }

            return(size);
        }
        private SizeRequest?SizeRequestDelegate(NativeViewWrapperRenderer renderer,
                                                int widthConstraint, int heightConstraint)
        {
            var size = new Xamarin.Forms.Size(200, 200);

            return(new SizeRequest(size));
        }
Example #6
0
        public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
        {
            var desiredSize = InternalMeasure(new Windows.Foundation.Size(widthConstraint, heightConstraint));
            var minSize     = new Xamarin.Forms.Size(10, Element != null ? _fontMetrics.LineHeightForFontSize(Element.DecipheredMinFontSize()) : 10);
            var result      = new SizeRequest(new Xamarin.Forms.Size(desiredSize.Width, desiredSize.Height), minSize);

            return(result);
        }
Example #7
0
        public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
        {
            DebugMessage("ENTER(" + widthConstraint + "," + heightConstraint + ")");
            var desiredSize = MeasureOverride(new Windows.Foundation.Size(widthConstraint, heightConstraint));
            var minSize     = new Xamarin.Forms.Size(10, Element != null ? FontExtensions.LineHeightForFontSize(Element.DecipheredMinFontSize()):10);

            DebugMessage("EXIT(" + desiredSize + ")");
            return(new SizeRequest(new Xamarin.Forms.Size(desiredSize.Width, desiredSize.Height), minSize));
        }
        protected internal void CalculateLayoutRects()
        {
            if (Element == null || Element.Width < 10 || _gridLayoutManager == null)
            {
                return;
            }


            var itemTemplate = Element.ItemTemplateSelector;

            if (!(itemTemplate is FastCollectionTemplateSelector templateSelector))
            {
                return;
            }
            templateSelector.Prepare();
            var width  = Element.Width;
            var widths = templateSelector.DataTemplates.Select(t => t.CellSize.Width);

            _columns = Math.Max(1, widths.Max(w => (int)(width / w)));

            _gridLayoutManager.SpanCount = _columns;
            if (_sizeLookup == null)
            {
                _sizeLookup = new GridSpanSizeLookup();
                _gridLayoutManager.SetSpanSizeLookup(_sizeLookup);
            }

            _sizeLookup.MaxColumns = _columns;
            _sizeLookup.Width      = width;

            var source        = Element.ItemsSource as ICollection;
            var numberOfItems = source?.Count ?? 0;

            var layoutInfo = new Size[numberOfItems];

            if (numberOfItems == 0 || source == null)
            {
                return;
            }
            var density = _density;

            var items = source.Cast <object>().ToArray();

            for (var i = 0; i < numberOfItems; i++)
            {
                var item = items[i];
                var size = GetSizeByItem(templateSelector, item);
                size.Height  *= density;
                size.Width   *= density;
                layoutInfo[i] = size;
            }

            var widthByPos = layoutInfo.Select(t => t.Width / density).ToList();

            _sizeLookup.WidthByPos = widthByPos;
        }
        public ImageDataModel GetImageData(string fileName)
        {
            UIImage image = UIImage.LoadFromData(new NSData());

            var result = new Xamarin.Forms.Size((double)image.Size.Width, (double)image.Size.Height);

            return(new ImageDataModel {
                Height = result.Height, Width = result.Width
            });
        }
Example #10
0
 public void SetElementSize(Xamarin.Forms.Size size)
 {
     if (this.loaded)
     {
         this.Element.Layout(new Xamarin.Forms.Rectangle(this.Element.X, this.Element.Y, size.Width, size.Height));
     }
     else
     {
         this.queuedSize = size;
     }
 }
Example #11
0
        public bool UpdateIconSize()
        {
            if (LayoutParameters is null)
            {
                throw new NullReferenceException(nameof(LayoutParameters));
            }

            Size size = GetIconSize();

            LayoutParameters.Width  = (int)_Cell.AndroidContext.ToPixels(size.Width);
            LayoutParameters.Height = (int)_Cell.AndroidContext.ToPixels(size.Height);
            return(true);
        }
Example #12
0
        /// <summary>
        /// Read in and resize image.
        /// </summary>
        /// <param name="v_sFilePath"></param>
        /// <param name="v_szSize"></param>
        /// <returns></returns>
        public async Task <object> ReadAndResizeImageFile(string v_sFilePath, Xamarin.Forms.Size v_szSize)
        {
            WriteableBitmap wbReturn = new WriteableBitmap((int)v_szSize.Width, (int)v_szSize.Height);

            try
            {
                StorageFile sfFile = await StorageFile.GetFileFromPathAsync(v_sFilePath);

                using (IRandomAccessStream fileStream = await sfFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    // Scale image to appropriate size
                    BitmapTransform transform = new BitmapTransform()
                    {
                        ScaledWidth  = Convert.ToUInt32(wbReturn.PixelWidth),
                        ScaledHeight = Convert.ToUInt32(wbReturn.PixelHeight)
                    };

                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,    // WriteableBitmap uses BGRA format
                        BitmapAlphaMode.Straight,
                        transform,
                        ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
                        ColorManagementMode.DoNotColorManage);

                    // An array containing the decoded image data, which could be modified before being displayed
                    byte[] sourcePixels = pixelData.DetachPixelData();

                    // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
                    using (Stream stream = wbReturn.PixelBuffer.AsStream())
                    {
                        await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
                    }
                }

                return(wbReturn);
            }
            catch (Exception ex)
            {
                //cMain.ReportError(ex, cMain.GetCallerMethodName(), string.Empty);
                return(null);
            }
        }
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            var size = new Xamarin.Forms.Size((int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density), (int)(Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density));

            Console.WriteLine(size.Height);
            Console.WriteLine(size.Width);

            App.screenSize.Width  = size.Width;
            App.screenSize.Height = size.Height;

            LoadApplication(new App());
        }
Example #14
0
        void UpdateIconSize()
        {
            Xamarin.Forms.Size size;
            if (CellBase.IconSize != default(Xamarin.Forms.Size))
            {
                size = CellBase.IconSize;
            }
            else if (CellParent != null && CellParent.CellIconSize != default(Xamarin.Forms.Size))
            {
                size = CellParent.CellIconSize;
            }
            else
            {
                size = new Xamarin.Forms.Size(36, 36);
            }

            IconView.LayoutParameters.Width  = (int)_Context.ToPixels(size.Width);
            IconView.LayoutParameters.Height = (int)_Context.ToPixels(size.Height);
        }
Example #15
0
        public static SizeRequest GetSizeRequest(
            this NSControl self,
            double widthConstraint,
            double heightConstraint,
            double minimumWidth  = -1.0,
            double minimumHeight = -1.0)
        {
            if (self == null)
            {
                return(new SizeRequest(
                           new Size(widthConstraint, heightConstraint),
                           new Size(minimumWidth, minimumHeight)));
            }

            CGSize cgSize = self.SizeThatFits((CGSize) new SizeF((float)widthConstraint, (float)heightConstraint));

            Xamarin.Forms.Size request = new Xamarin.Forms.Size(cgSize.Width == (nfloat)float.PositiveInfinity ? double.PositiveInfinity : (double)cgSize.Width, cgSize.Height == (nfloat)float.PositiveInfinity ? double.PositiveInfinity : (double)cgSize.Height);
            Xamarin.Forms.Size minimum = new Xamarin.Forms.Size(minimumWidth < 0.0 ? request.Width : minimumWidth, minimumHeight < 0.0 ? request.Height : minimumHeight);
            return(new SizeRequest(request, minimum));
        }
Example #16
0
        CAShapeLayer GetMaskShape(ViewMaskerType maskType, Xamarin.Forms.Size size)
        {
            var layer = new CAShapeLayer();

            layer.FillColor   = UIColor.White.CGColor;
            layer.StrokeColor = UIColor.White.CGColor;
            layer.LineWidth   = 0;
            UIBezierPath path   = null;
            var          bounds = new CGRect(0, 0, size.Width, size.Height);

            switch (maskType)
            {
            case ViewMaskerType.Circle:
                path = UIBezierPath.FromRoundedRect(bounds, (nfloat)Math.Max(size.Width, size.Height));
                break;

            case ViewMaskerType.Triangle:
                var point1 = new CGPoint(0, size.Height);
                var point2 = new CGPoint(size.Width, size.Height);
                var point3 = new CGPoint(size.Width / 2, 0);
                path = new UIBezierPath();
                path.MoveTo(point1);
                path.AddLineTo(point2);
                path.AddLineTo(point3);
                path.AddLineTo(point1);
                path.ClosePath();
                path.Fill();
                break;

            case ViewMaskerType.Square:
                var smallRectangle = UIBezierPath.FromRect(bounds.Inset(50, 50));
                path = UIBezierPath.FromRoundedRect(bounds, 20);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            layer.Path = path.CGPath;
            return(layer);
        }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="v_sfFrom"></param>
        /// <param name="v_sfTo"></param>
        public async Task <bool> CopyAndConvertImage(object v_sfFrom, object v_sfTo, Xamarin.Forms.Size v_szSize)
        {
            try
            {
                using (IRandomAccessStream fileStream = await((StorageFile)v_sfFrom).OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                    // Scale image to appropriate size
                    BitmapTransform transform = new BitmapTransform()
                    {
                        ScaledWidth  = Convert.ToUInt32(v_szSize.Width),
                        ScaledHeight = Convert.ToUInt32(v_szSize.Height)
                    };

                    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,    // WriteableBitmap uses BGRA format
                        BitmapAlphaMode.Straight,
                        transform,
                        ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
                        ColorManagementMode.DoNotColorManage);


                    using (var destinationStream = await((StorageFile)v_sfTo).OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);

                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)v_szSize.Width, (uint)v_szSize.Height, 72, 72, pixelData.DetachPixelData());
                        await encoder.FlushAsync();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                //cMain.ReportError(ex, cMain.GetCallerMethodName(), string.Empty);
                return(false);
            }
        }
Example #18
0
        public Border(Border border)
        {
            LeftWidth   = border.LeftWidth;
            TopWidth    = border.TopWidth;
            RightWidth  = border.RightWidth;
            BottomWidth = border.BottomWidth;

            LeftStyle   = border.LeftStyle;
            TopStyle    = border.TopStyle;
            RightStyle  = border.RightStyle;
            BottomStyle = border.BottomStyle;

            LeftColor   = border.LeftColor;
            TopColor    = border.TopColor;
            RightColor  = border.RightColor;
            BottomColor = border.BottomColor;

            BottomLeft  = border.BottomLeft;
            BottomRight = border.BottomRight;
            TopLeft     = border.TopLeft;
            TopRight    = border.TopRight;
        }
Example #19
0
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var gridViewCell = Element.ItemTemplate.CreateContent() as FastGridCell;

            var initialCellSize = new Xamarin.Forms.Size(Element.ItemWidth, Element.ItemHeight);
            var view            = new GridViewCellContainer(parent.Context, gridViewCell, parent, initialCellSize);

            view.Click += mMainView_Click;

            var width = Convert.ToInt32(Element.ItemWidth);
            //TODO the height is just not working out correctly for us - views end up being too small
            var height = Convert.ToInt32(Element.ItemHeight + _gridView.RowSpacing);
            var dpW    = ConvertDpToPixels(width);
            var dpH    = ConvertDpToPixels(height);

            view.SetMinimumWidth(dpW);
            view.SetMinimumHeight(dpH);

            view.LayoutParameters = new  GridLayoutManager.LayoutParams(dpW, dpH);
            GridViewCell myView = new GridViewCell(view);

            return(myView);
        }
Example #20
0
        public override void ViewDidLayoutSubviews()
        {
            // ISSUE: reference to a compiler-generated method
            base.ViewDidLayoutSubviews();
            if (this.Element == null)
            {
                return;
            }
            if (!this.Element.Bounds.IsEmpty)
            {
                this.View.Frame = (CGRect) new RectangleF((float)this.Element.X, (float)this.Element.Y, (float)this.Element.Width, (float)this.Element.Height);
            }
            CGRect frame1 = this.View.Frame;
            CGRect frame2 = this.TabBar.Frame;

            ((Page)this.Element).ContainerArea = new Xamarin.Forms.Rectangle(0.0, 0.0, (double)frame1.Width, (double)(frame1.Height - frame2.Height));
            if (!this.queuedSize.IsZero)
            {
                this.Element.Layout(new Xamarin.Forms.Rectangle(this.Element.X, this.Element.Y, this.queuedSize.Width, this.queuedSize.Height));
                this.queuedSize = Xamarin.Forms.Size.Zero;
            }
            this.loaded = true;
        }
Example #21
0
 public void SetElementSize(Xamarin.Forms.Size size)
 {
     this.Element.Layout(new Xamarin.Forms.Rectangle(this.Element.X, this.Element.Y, size.Width, size.Height));
 }
        void SetImages(MvvmAspire.Controls.Button element)
        {
            try
            {
                ButtonText = Element.Text;

                if (!HaseResource(element.ImageLeft) && !HaseResource(element.ImageTop) && !HaseResource(element.ImageRight) && !HaseResource(element.ImageBottom))
                {
                    Control.SetCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                    Control.Invalidate();
                    return;
                }

                Drawable leftResource = null, topResource = null, rightResource = null, bottomResource = null;

                if (element.ImageLeft != null && element.ImageLeft.File != null)
                {
                    leftResource = ContextCompat.GetDrawable(UIHelper.Context, UIHelper.GetDrawableResource(element.ImageLeft));
                }
                if (element.ImageTop != null && element.ImageTop.File != null)
                {
                    topResource = ContextCompat.GetDrawable(UIHelper.Context, UIHelper.GetDrawableResource(element.ImageTop));
                }
                if (element.ImageRight != null && element.ImageRight.File != null)
                {
                    rightResource = ContextCompat.GetDrawable(UIHelper.Context, UIHelper.GetDrawableResource(element.ImageRight));
                }
                if (element.ImageBottom != null && element.ImageBottom.File != null)
                {
                    bottomResource = ContextCompat.GetDrawable(UIHelper.Context, UIHelper.GetDrawableResource(element.ImageBottom));
                }

                bool hasResource = leftResource != null || rightResource != null || topResource != null || bottomResource != null;
                if (hasResource && !element.CenterImage)
                {
                    Control.SetCompoundDrawablesWithIntrinsicBounds(leftResource, topResource, rightResource, bottomResource);
                }

                if (hasResource && element.CenterImage)
                {
                    Xamarin.Forms.Size size = new Xamarin.Forms.Size();

                    if (leftResource != null)
                    {
                        if (element.ImageLeftHeight > 0 && element.ImageLeftWidth > 0)
                        {
                            size.Width  = element.ImageLeftWidth;
                            size.Height = element.ImageLeftHeight;
                        }
                        else
                        {
                            var maxWidth  = BaseUIHelper.ConvertDPToPixels(element.Padding.Left) - BaseUIHelper.ConvertDPToPixels(element.Padding.Right) - Control.MeasuredWidth;
                            var maxHeight = BaseUIHelper.ConvertDPToPixels(element.Padding.Top) - BaseUIHelper.ConvertDPToPixels(element.Padding.Bottom) - Control.MeasuredHeight;

                            var temp = GetSize(leftResource.IntrinsicWidth, leftResource.IntrinsicHeight, Math.Abs(maxWidth), Math.Abs(maxHeight));
                            size.Width  = temp.Width;
                            size.Height = temp.Height;
                        }

                        var scaledDrawable = new ScaleDrawable(leftResource, 0, (int)size.Width, (int)size.Height).Drawable;
                        scaledDrawable.SetBounds(0, 0, (int)size.Width, (int)size.Height);

                        Control.SetCompoundDrawables(scaledDrawable, null, null, null);
                    }

                    if (rightResource != null)
                    {
                        if (element.ImageRightHeight > 0 && element.ImageRightWidth > 0)
                        {
                            size.Width  = element.ImageRightWidth;
                            size.Height = element.ImageRightHeight;
                        }
                        else
                        {
                            var maxWidth  = BaseUIHelper.ConvertDPToPixels(element.Padding.Left) - BaseUIHelper.ConvertDPToPixels(element.Padding.Right) - Control.MeasuredWidth;
                            var maxHeight = BaseUIHelper.ConvertDPToPixels(element.Padding.Top) - BaseUIHelper.ConvertDPToPixels(element.Padding.Bottom) - Control.MeasuredHeight;
                            var temp      = GetSize(rightResource.IntrinsicWidth, rightResource.IntrinsicHeight, Math.Abs(maxWidth), Math.Abs(maxHeight));
                            size.Width  = temp.Width;
                            size.Height = temp.Height;
                        }

                        var scaledDrawable = new ScaleDrawable(rightResource, 0, (int)size.Width, (int)size.Height).Drawable;
                        scaledDrawable.SetBounds(0, 0, (int)size.Width, (int)size.Height);

                        Control.SetCompoundDrawables(null, null, scaledDrawable, null);
                    }

                    if (!element.CenterImage)
                    {
                        SetImagePadding((int)size.Width);
                    }

                    Control.Invalidate();
                }
            }
            catch (Exception e)
            {
            }
        }
Example #23
0
        protected Windows.Foundation.Size InternalMeasure(Windows.Foundation.Size availableSize, TextBlock control = null)
        {
            if (Element is Forms9Patch.Label element)
            {
                control = control ?? Control;
                if (control == null || availableSize.Width <= 0 || availableSize.Height <= 0)
                {
                    _lastAvailableSize = availableSize;
                    _lastElementSize   = element.Bounds.Size;
                    return(new Windows.Foundation.Size(0, 0));
                }
                // Next block was commented out because of failure to render BcNotes in Heights and Areas (in notes popup and on Disclaimer)
                // ... and, by doing so, it broke the picker and the keypad in Heights and Areas.
                if (LayoutValid &&
                    control == Control &&
                    _lastAvailableSize.Width == availableSize.Width &&
                    _lastAvailableSize.Height == availableSize.Height &&
                    _lastElementSize == element.Bounds.Size &&
                    DateTime.Now - _lastMeasure < TimeSpan.FromSeconds(1))
                {
                    return(_lastInternalMeasure);
                }

                element.SetIsInNativeLayout(true);

                var width  = Math.Min(availableSize.Width, int.MaxValue / 2);
                var height = Math.Min(availableSize.Height, int.MaxValue / 2);
                var result = new Windows.Foundation.Size(width, height);

                if (control != null)
                {
                    // reset FontSize
                    var tmpFontSize = element.DecipheredFontSize();

                    if (element.SynchronizedFontSize > element.MinFontSize)
                    {
                        tmpFontSize = element.SynchronizedFontSize;
                    }
                    var minFontSize = element.DecipheredMinFontSize();
                    control.MaxLines  = 0; // int.MaxValue / 3;
                    control.MaxWidth  = double.PositiveInfinity;
                    control.MaxHeight = double.PositiveInfinity;
                    control.MinHeight = 0;
                    control.MinWidth  = 0;

                    control.FontStyle  = element.FontAttributes.HasFlag(FontAttributes.Italic) ? FontStyle.Italic : FontStyle.Normal;
                    control.FontWeight = element.FontAttributes.HasFlag(FontAttributes.Bold) ? FontWeights.Bold : FontWeights.Normal;

                    control.UpdateLineBreakMode(element);

                    control.SetAndFormatText(element, tmpFontSize);
                    control.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                    double tmpHt = control.DesiredSize.Height;
                    _fontMetrics = control.GetFontMetrics();
                    if (element.Lines == 0)
                    {
                        // do our best job to fit the existing space.
                        if (control.DesiredSize.Width - width > -Precision || control.DesiredSize.Height - height > -Precision)
                        {
                            if (DebugCondition)
                            {
                                System.Diagnostics.Debug.WriteLine(GetType() + ".");
                            }
                            tmpFontSize = ZeroLinesFit(element, control, minFontSize, tmpFontSize, width, height);
                            if (DebugCondition)
                            {
                                System.Diagnostics.Debug.WriteLine(GetType() + ".");
                            }
                            control.SetAndFormatText(element, tmpFontSize);
                            control.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                            tmpHt = control.DesiredSize.Height;
                        }
                    }
                    else if (element.AutoFit == AutoFit.Lines)
                    {
                        tmpHt = height;
                        if (height > int.MaxValue / 3)
                        {
                            tmpHt = height = _fontMetrics.HeightForLinesAtFontSize(element.Lines, tmpFontSize);
                        }
                        else
                        {
                            // set the font size to fit Label.Lines into the available height
                            var constrainedSize = control.DesiredSize;

                            tmpFontSize = _fontMetrics.FontSizeFromLinesInHeight(element.Lines, tmpHt);
                            tmpFontSize = FontExtensions.ClipFontSize(tmpFontSize, element);

                            control.SetAndFormatText(element, tmpFontSize);
                            control.Measure(new Windows.Foundation.Size(double.PositiveInfinity, double.PositiveInfinity));
                            if (element.Lines > 1)
                            {
                                var unconstrainedSize = control.DesiredSize;
                                if (unconstrainedSize.Width > constrainedSize.Width)
                                {
                                    control.SetAndFormatText(element, tmpFontSize);
                                    control.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                                }
                            }
                        }
                    }
                    else if (element.AutoFit == AutoFit.Width)
                    {
                        if (control.ActualWidth > control.DesiredSize.Width || control.DesiredSize.Height / control.LineHeight > element.Lines)
                        {
                            tmpFontSize = WidthAndLinesFit(element, control, element.Lines + 1, minFontSize, tmpFontSize, width);
                            control.SetAndFormatText(element, tmpFontSize);
                            control.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                            tmpHt = control.DesiredSize.Height;
                        }
                    }

                    // none of these should happen so let's keep an eye out for it to be sure everything upstream is working
                    if (tmpFontSize > element.DecipheredFontSize())
                    {
                        throw new Exception("fitting somehow returned a tmpFontSize > label.FontSize");
                    }
                    if (tmpFontSize < element.DecipheredMinFontSize())
                    {
                        throw new Exception("fitting somehow returned a tmpFontSize < label.MinFontSize");
                    }
                    // the following doesn't apply when where growing
                    //if (tmpFontSize > label.DecipheredMinFontSize() && (control.DesiredSize.Width > Math.Ceiling(w) || control.DesiredSize.Height > Math.Ceiling(Math.Max(availableSize.Height, label.Height))) )
                    //    throw new Exception("We should never exceed the available bounds if the FontSize is greater than label.MinFontSize");

                    // we needed the following in Android as well.  Xamarin layout really doesn't like this to be changed in real time.
                    if (element != null && Control == control)  // multipicker test was getting here with element and Control both null
                    {
                        if (tmpFontSize == element.FontSize || (element.FontSize == -1 && tmpFontSize == FontExtensions.DefaultFontSize()))
                        {
                            element.FittedFontSize = -1;
                        }
                        else if (Math.Abs(element.FittedFontSize - tmpFontSize) > 1)
                        {
                            element.FittedFontSize = tmpFontSize;
                        }
                    }

                    result           = new Windows.Foundation.Size(Math.Ceiling(control.DesiredSize.Width), Math.Ceiling(tmpHt));
                    control.MaxLines = element.Lines;
                }

                element.SetIsInNativeLayout(false);

                if (control == Control)
                {
                    LayoutValid        = true;
                    _lastAvailableSize = availableSize;
                    _lastElementSize   = element.Bounds.Size;
                    //_lastAutoFit = label.AutoFit;
                    //_lastLines = label.Lines;
                    _lastMeasure         = DateTime.Now;
                    _lastInternalMeasure = result;

                    PrivateArrange(availableSize);
                }
                return(result);
            }
            return(Windows.Foundation.Size.Empty);
        }
Example #24
0
 public static SizeF ToSizeF(this Size size)
 {
     return new SizeF((float)size.Width, (float)size.Height);
 }
Example #25
0
 //public GridViewCellContainer(Context context, JWChinese.GridViewCell viewCell, global::Android.Views.View parent, Xamarin.Forms.Size initialCellSize) : base(context)
 public GridViewCellContainer(Context context, ViewCell viewCell, global::Android.Views.View parent, Xamarin.Forms.Size initialCellSize) : base(context)
 {
     using (var h = new Handler(Looper.MainLooper))
     {
         h.Post(() =>
         {
             _parent   = parent;
             _viewCell = viewCell;
             //_viewCell.PrepareCell(initialCellSize);
             var renderer = Platform.GetRenderer(viewCell.View);
             if (renderer == null)
             {
                 renderer = Platform.CreateRenderer(viewCell.View);
                 Platform.SetRenderer(viewCell.View, renderer);
             }
             _nativeView = renderer.ViewGroup;
             AddView(_nativeView);
         });
     }
 }
        public static void resizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
        {
            if (!File.Exists(targetFile) && File.Exists(sourceFile))
            {
                // First decode with inJustDecodeBounds=true to check dimensions
                var options = new BitmapFactory.Options()
                {
                    InJustDecodeBounds = false,
                    InPurgeable        = true,
                };

                using (var image = BitmapFactory.DecodeFile(sourceFile, options))
                {
                    if (image != null)
                    {
                        var sourceSize = new Xamarin.Forms.Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);

                        var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);

                        string targetDir = System.IO.Path.GetDirectoryName(targetFile);
                        if (!Directory.Exists(targetDir))
                        {
                            Directory.CreateDirectory(targetDir);
                        }

                        if (maxResizeFactor > 0.9)
                        {
                            File.Copy(sourceFile, targetFile);
                        }
                        else
                        {
                            var width  = (int)(maxResizeFactor * sourceSize.Width);
                            var height = (int)(maxResizeFactor * sourceSize.Height);

                            /*
                             * Bitmap scaledBitmap = Bitmap.CreateScaledBitmap(image, width, height, false);
                             * VideoThumbnailHelper.exportBitmapAsPNGAsync(targetFile, scaledBitmap);
                             */


                            using (var bitmapScaled = Bitmap.CreateScaledBitmap(image, height, width, true))
                            {
                                using (Stream outStream = File.Create(targetFile))
                                {
                                    if (targetFile.ToLower().EndsWith("png"))
                                    {
                                        bitmapScaled.Compress(Bitmap.CompressFormat.Png, 100, outStream);
                                    }
                                    else
                                    {
                                        bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream);
                                    }
                                }
                                bitmapScaled.Recycle();
                            }
                        }

                        image.Recycle();
                    }
                    else
                    {
                        throw new Exception("ImageResizeHelper.cs - Image scaling failed of " + sourceFile);
                    }
                }
            }
        }
Example #27
0
        protected override Windows.Foundation.Size MeasureOverride(Windows.Foundation.Size availableSize)
        {
            if (DebugCondition)
            {
                System.Diagnostics.Debug.WriteLine("");
            }


            var label     = Element;
            var textBlock = Control;

            DebugMessage("[" + _measureOverrideInvocation + "] MeasureOverride pre-Enter availableSize=[" + availableSize + "] ElemmentSize=[" + Element.Bounds.Size + "]  PageSize=[" + Xamarin.Forms.Application.Current.MainPage.Bounds.Size + "]");
            DebugMessage("[" + _measureOverrideInvocation + "] \t\t availWidth>=Page.Width=[" + (Math.Round(availableSize.Width) >= Math.Round(Xamarin.Forms.Application.Current.MainPage.Width)) + "]");
            DebugMessage("[" + _measureOverrideInvocation + "] \t\t availHeight>=Page.Height=[" + (Math.Round(availableSize.Height) >= Math.Round(Xamarin.Forms.Application.Current.MainPage.Height)) + "]");
            DebugMessage("[" + _measureOverrideInvocation + "] \t\t Element.Parent=[" + Element.Parent + "]");
            DebugMessage("[" + _measureOverrideInvocation + "] \t\t MeasureOverride FontSize=[" + textBlock.FontSize + "] BaseLineOffset=[" + textBlock.BaselineOffset + "] LineHeight=[" + textBlock.LineHeight + "]");

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



            if (label == null || textBlock == null || availableSize.Width == 0 || availableSize.Height == 0)
            {
                return(new Windows.Foundation.Size(0, 0));
            }

            //if (Double.IsInfinity(availableSize.Height) && Double.IsInfinity(availableSize.Width))
            //    LayoutValid = false;

            if (LayoutValid && _lastAvailableSize.Width <= availableSize.Width && _lastAvailableSize.Height <= availableSize.Height && _lastElementSize == Element.Bounds.Size && DateTime.Now - _lastMeasure < TimeSpan.FromSeconds(1))
            {
                return(_lastMeasureOverrideResult);
            }

            //_lastAvailableSize = availableSize;
            if (DebugCondition)
            {
                System.Diagnostics.Debug.WriteLine("");
            }

            DebugMessage("[" + _measureOverrideInvocation + "] MeasureOverride ENTER availableSize=[" + availableSize + "]");
            //Element.IsInNativeLayout = true;
            label.SetIsInNativeLayout(true);

            double width  = (Math.Round(availableSize.Width) >= Math.Round(Xamarin.Forms.Application.Current.MainPage.Width)) && label.Width > 0 ? Math.Min(label.Width, availableSize.Width) : availableSize.Width;
            double height = (Math.Round(availableSize.Height) >= Math.Round(Xamarin.Forms.Application.Current.MainPage.Height)) && label.Height > 0 ? Math.Min(label.Height, availableSize.Height) : availableSize.Height;


            if (Double.IsInfinity(availableSize.Width) && (label.Width < 0 || !newElement))
            {
                width = availableSize.Width;
            }
            if (Double.IsInfinity(availableSize.Height) && (label.Height < 0 || !newElement))
            {
                height = availableSize.Height;
            }

            newElement = false;


            if (Element.Width > 0 && Element.Height > 0 && !Double.IsInfinity(width) && !Double.IsInfinity(height))  // This line was causing UWP to fail to correctly update width of BcOperandLabel during editing.
            //if (Element.Width > width && Element.Height > height && !Double.IsInfinity(width) && !Double.IsInfinity(height))
            {
                width  = Math.Max(Element.Width, width);
                height = Math.Max(Element.Height, height);
            }

            DebugMessage("[" + _measureOverrideInvocation + "] \t\t width=[" + width + "] height=[" + height + "]");
            if (DebugCondition)
            {
                System.Diagnostics.Debug.WriteLine("");
            }

            //double width = !double.IsInfinity(availableSize.Width) && label.Width > 0 ? Math.Min(label.Width, availableSize.Width) : availableSize.Width;
            //double height = !double.IsInfinity(availableSize.Height) && label.Height > 0 ? Math.Min(label.Height, availableSize.Height) : availableSize.Height;
            //double width  = availableSize.Width;
            //double height = availableSize.Height;

            var result = new Windows.Foundation.Size(width, height);

            if (textBlock != null)
            {
                // reset FontSize
                var tmpFontSize = label.DecipheredFontSize();

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

                if (Element.SynchronizedFontSize > Element.MinFontSize)
                {
                    tmpFontSize = Element.SynchronizedFontSize;
                }
                var minFontSize = label.DecipheredMinFontSize();
                textBlock.MaxLines  = 0; // int.MaxValue / 3;
                textBlock.MaxWidth  = double.PositiveInfinity;
                textBlock.MaxHeight = double.PositiveInfinity;
                textBlock.MinHeight = 0;
                textBlock.MinWidth  = 0;
                //textBlock.LineStackingStrategy = LineStackingStrategy.
                //  textBlock.TextWrapping = TextWrapping.WrapWholeWords;
                UpdateLineBreakMode(textBlock);

                double tmpHt = -1;

                textBlock.SetAndFormatText(label, tmpFontSize);
                textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                _fontMetrics = textBlock.GetFontMetrics();
                if (label.Lines == 0)
                {
                    // do our best job to fit the existing space.
                    if (textBlock.DesiredSize.Width - width > Precision || textBlock.DesiredSize.Height - height > Precision)
                    {
                        tmpFontSize = ZeroLinesFit(label, textBlock, minFontSize, tmpFontSize, width, height);

                        textBlock.SetAndFormatText(label, tmpFontSize);
                        textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                    }
                }
                else if (label.AutoFit == AutoFit.Lines)
                {
                    tmpHt = height;
                    if (height > int.MaxValue / 3)
                    {
                        //tmpHt = height = label.Lines * (_fontMetrics.LineHeightForFontSize(tmpFontSize) + ;
                        tmpHt = height = _fontMetrics.HeightForLinesAtFontSize(label.Lines, tmpFontSize);
                    }
                    else
                    {// set the font size to fit Label.Lines into the available height
                        //tmpFontSize = _fontMetrics.FontSizeFromLineHeight(height / label.Lines);
                        tmpFontSize = _fontMetrics.FontSizeFromLinesInHeight(label.Lines, tmpHt);

                        tmpFontSize = FontExtensions.ClipFontSize(tmpFontSize, label);

                        textBlock.SetAndFormatText(label, tmpFontSize);
                        textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                    }
                }
                else if (label.AutoFit == AutoFit.Width)
                {
                    //if (textBlock.DesiredSize.Height / textBlock.LineHeight > label.Lines)
                    if (textBlock.ActualWidth > textBlock.DesiredSize.Width || textBlock.DesiredSize.Height / textBlock.LineHeight > label.Lines)
                    {
                        tmpFontSize = WidthAndLinesFit(label, textBlock, label.Lines, minFontSize, tmpFontSize, width);

                        textBlock.SetAndFormatText(label, tmpFontSize);
                        textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                    }
                }
                // autofit is off!
                // No need to do anything at the moment.  Will textBlock.SetAndFormat and textBlock.Measure at the end
                //{
                //    textBlock.SetAndFormatText(label, tmpFontSize);
                //    textBlock?.Measure(new Windows.Foundation.Size(w, double.PositiveInfinity));
                //}

                // none of these should happen so let's keep an eye out for it to be sure everything upstream is working
                if (tmpFontSize > label.DecipheredFontSize())
                {
                    throw new Exception("fitting somehow returned a tmpFontSize > label.FontSize");
                }
                if (tmpFontSize < label.DecipheredMinFontSize())
                {
                    throw new Exception("fitting somehow returned a tmpFontSize < label.MinFontSize");
                }
                // the following doesn't apply when where growing
                //if (tmpFontSize > label.DecipheredMinFontSize() && (textBlock.DesiredSize.Width > Math.Ceiling(w) || textBlock.DesiredSize.Height > Math.Ceiling(Math.Max(availableSize.Height, label.Height))) )
                //    throw new Exception("We should never exceed the available bounds if the FontSize is greater than label.MinFontSize");



                // we needed the following in Android as well.  Xamarin layout really doesn't like this to be changed in real time.
                if (Element != null && Control != null)  // multipicker test was getting here with Element and Control both null
                {
                    if (tmpFontSize == Element.FontSize || (Element.FontSize == -1 && tmpFontSize == FontExtensions.DefaultFontSize()))
                    {
                        if (DebugCondition)
                        {
                            System.Diagnostics.Debug.WriteLine("");
                        }
                        Element.FittedFontSize = -1;
                    }
                    else
                    {
                        if (DebugCondition)
                        {
                            System.Diagnostics.Debug.WriteLine("");
                        }
                        Element.FittedFontSize = tmpFontSize;
                    }
                }
                DebugMessage("[" + _measureOverrideInvocation + "] MeasureOverride Element.FittedFontSize=[" + Element.FittedFontSize + "]");

                /*
                 * var syncFontSize = ((ILabel)label).SynchronizedFontSize;
                 * DebugMessage("[" + _measureOverrideInvocation + "] syncFontSize=[" + syncFontSize+"]");
                 * if (syncFontSize >= 0 && tmpFontSize != syncFontSize)
                 * {
                 *  tmpHt = -1;
                 *  textBlock.SetAndFormatText(label, syncFontSize);
                 *  textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                 * }
                 * else
                 * {
                 *  textBlock.SetAndFormatText(label, tmpFontSize);
                 *  textBlock.Measure(new Windows.Foundation.Size(width, double.PositiveInfinity));
                 * }
                 */
                result = new Windows.Foundation.Size(Math.Ceiling(textBlock.DesiredSize.Width), Math.Ceiling(tmpHt > -1 ? tmpHt : textBlock.DesiredSize.Height));

                if (DebugCondition && label.Width > 0 && label.Height > 0 && (textBlock.DesiredSize.Width > label.Width || textBlock.DesiredSize.Height > label.Height))
                {
                    System.Diagnostics.Debug.WriteLine("");
                }
                DebugMessage("[" + _measureOverrideInvocation + "] availableSize=[" + availableSize + "] result=[" + result + "] FontSize=[" + textBlock.FontSize + "] LineHeight=[" + textBlock.LineHeight + "] ");
                //System.Diagnostics.Debug.WriteLine("[" + _measureOverrideInvocation + "] MeasureOverride [" + (Element.Text ?? Element.HtmlText)+"] availableSize=[" + availableSize + "] result=[" + result + "] FontSize=[" + textBlock.FontSize + "] LineHeight=[" + textBlock.LineHeight + "] ");

                textBlock.MaxLines = label.Lines;
            }

            label.SetIsInNativeLayout(false);

            DebugMessage("[" + _measureOverrideInvocation + "] MeasureOverride EXIT");

            LayoutValid                = true;
            _lastAvailableSize         = availableSize;
            _lastElementSize           = Element.Bounds.Size;
            _lastAutoFit               = label.AutoFit;
            _lastLines                 = label.Lines;
            _lastMeasure               = DateTime.Now;
            _lastMeasureOverrideResult = result;

            if (DebugCondition)
            {
                _measureOverrideInvocation++;
            }

            return(result);
        }
Example #28
0
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var gridViewCell = Element.ItemTemplate.CreateContent () as FastGridCell;

            var initialCellSize = new Xamarin.Forms.Size (Element.ItemWidth, Element.ItemHeight);
            var view = new GridViewCellContainer (parent.Context, gridViewCell, parent, initialCellSize);
            view.Click += mMainView_Click;

            var width = Convert.ToInt32 (Element.ItemWidth);
            //TODO the height is just not working out correctly for us - views end up being too small
            var height = Convert.ToInt32 (Element.ItemHeight + _gridView.RowSpacing);
            var dpW = ConvertDpToPixels (width);
            var dpH = ConvertDpToPixels (height);
            view.SetMinimumWidth (dpW);
            view.SetMinimumHeight (dpH);

            view.LayoutParameters = new  GridLayoutManager.LayoutParams (dpW, dpH);
            GridViewCell myView = new GridViewCell (view);

            return myView;
        }
		public Xamarin.Forms.Size GetCameraSize()
		{
			Xamarin.Forms.Size camSize = new  Xamarin.Forms.Size ();
			return camSize;
		}