public void Close(bool animated = true) { if (animated) { UIView.Animate(0.15, delegate { Transform = CGAffineTransform.MakeScale(0.1f, 0.1f); effectView.Alpha = 0; }, delegate { this.RemoveFromSuperview(); effectView.RemoveFromSuperview(); if (null != PopWillClose) { PopWillClose(); } }); } else { if (null != PopWillClose) { PopWillClose(); } } }
public static void StartAnimation(this MaterialShowcase materialShowcase) { //UIViewAnimationOptions optionsOLD = UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Repeat; UIViewKeyframeAnimationOptions options = UIViewKeyframeAnimationOptions.Repeat | 0 << 16; UIView.AnimateKeyframes(1, 0, options, () => { UIView.AddKeyframeWithRelativeStartTime(0, .5f, () => { materialShowcase.targetRippleView.Alpha = MaterialShowcase.AniRippleAlpha; materialShowcase.targetHolderView.Transform = CGAffineTransform.MakeScale(1.1f, 1.1f); materialShowcase.targetRippleView.Transform = CGAffineTransform.MakeScale(1.1f, 1.1f); }); UIView.AddKeyframeWithRelativeStartTime(.5f, .5f, () => { materialShowcase.targetHolderView.Transform = CGAffineTransform.MakeIdentity(); materialShowcase.targetRippleView.Alpha = 0; materialShowcase.targetRippleView.Transform = CGAffineTransform.MakeScale(materialShowcase.aniRippleScale, materialShowcase.aniRippleScale); }); }, (completion) => { Console.WriteLine("ok"); }); }
private void SetupCell() { //TODO: Replace this with thumbnail url this.WhenAnyValue(x => x.ViewModel.ThumbnailUrl) .Where(t => !string.IsNullOrEmpty(t)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(async t => { var thumbNail = await MobileCore.PDRMobileRepository.Current.DownloadPhotoAsync(t, 100f, 100f); if (thumbNail == null) { return; } await UIView.AnimateAsync(Constants.Animation.StandardAnimationDuration, async() => { image.Image = thumbNail.ToNative(); image.Alpha = 1.0f; }); }); this.ContentView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; ContentView.Transform = CGAffineTransform.MakeScale(.95f, .95f); BackgroundView = new UIView { BackgroundColor = MobileCore.Values.Colors.Orange.ToNative() }; image = new UIImageView(); image.ContentMode = UIViewContentMode.ScaleAspectFill; ContentView.Add(image); this.ContentView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints(); SetNeedsUpdateConstraints(); }
void setbuton(int i) { BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; ContentView.Layer.BorderColor = UIColor.Blue.CGColor; ContentView.Layer.BorderWidth = 2.0f; ContentView.BackgroundColor = UIColor.White; ContentView.Transform = CGAffineTransform.MakeScale(0.8f, 0.8f); // imageView = new UIImageView(UIImage.FromBundle("placeholder.png")); // button.Center = ContentView.Center; // button.Transform = CGAffineTransform.MakeScale(0.7f, 0.7f); local.UIbutton[i].Frame(0, 0, (75)); ContentView.AddSubview(local.UIbutton[i].RButton()); }
public SensorCell(CGRect frame) : base(frame) { BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; ContentView.Layer.BorderWidth = 2.0f; ContentView.BackgroundColor = UIColor.White; ContentView.Transform = CGAffineTransform.MakeScale(0.8f, 0.8f); _textLabel = new UILabel(); _textLabel.Lines = 2; _textLabel.BackgroundColor = UIColor.Clear; _textLabel.TextColor = UIColor.DarkGray; _textLabel.TextAlignment = UITextAlignment.Center; ContentView.AddSubview(_textLabel); }
private void showTimeEntryCard() { StopTimeEntryButton.Hidden = false; CurrentTimeEntryCard.Hidden = false; cardAnimationCancellation?.Cancel(); cardAnimationCancellation = new CancellationTokenSource(); TimeEntriesLogTableViewBottomToTopCurrentEntryConstraint.Active = true; AnimationExtensions.Animate(Timings.EnterTiming, showCardDelay, Curves.EaseOut, () => StartTimeEntryButton.Transform = CGAffineTransform.MakeScale(0.01f, 0.01f), () => { AnimationExtensions.Animate(Timings.LeaveTimingFaster, Curves.EaseIn, () => StopTimeEntryButton.Transform = CGAffineTransform.MakeScale(1.0f, 1.0f), cancellationToken: cardAnimationCancellation.Token); AnimationExtensions.Animate(Timings.LeaveTiming, Curves.CardOutCurve, () => CurrentTimeEntryCard.Transform = CGAffineTransform.MakeTranslation(0, 0), cancellationToken: cardAnimationCancellation.Token); }, cancellationToken: cardAnimationCancellation.Token); }
private void HandleTouchUpInsideButton(object sender, EventArgs e) { var button = sender as UIButton; var satelliteMenuButtonItem = _menuItems[_buttonItems.IndexOf(button)]; satelliteMenuButtonItem.FireClick(satelliteMenuButtonItem, EventArgs.Empty); MenuItemClick?.Invoke(sender, new SatelliteMenuItemEventArgs { MenuItem = satelliteMenuButtonItem }); Animate(0.15, delegate { if (button != null) { button.Transform = CGAffineTransform.MakeScale(1.2f, 1.2f); } }, delegate { if (CloseItemsOnClick) { Collapse(); } }); }
public override void TouchesEnded(NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); var touch = touches.AnyObject as UITouch; if (touch == null || imageIsMoving == false) { return; } if (boxOne.Frame.Contains(imgLogo.Center) == true) { UIView.Animate(0.5, () => { imgLogo.Center = boxOne.Center; imgLogo.Transform = CGAffineTransform.MakeScale(0.5f, 0.5f); }); } else if (boxTwo.Frame.Contains(imgLogo.Center) == true) { UIView.Animate(0.5, () => { imgLogo.Center = boxTwo.Center; imgLogo.Transform = CGAffineTransform.MakeScale(0.5f, 0.5f); }); } else { UIView.Animate(0.25, () => { imgLogo.Center = this.View.Center; imgLogo.Transform = CGAffineTransform.MakeScale(1, 1); }); } imageIsMoving = false; }
public static UIImage ScaleAndRotateImage(this UIImage image, int maxResolution) { if (image.Size.Width < maxResolution && image.Size.Height < maxResolution) { return(image); } //CGImage imgRef = image.CGImage; using (CGImage imgRef = image.CGImage) { float width = imgRef.Width; float height = imgRef.Height; //int kMaxResolution = (int)Math.Max (width, height); // use current size of picture (not scale or resize) int kMaxResolution = maxResolution; // based on customer's idea CGAffineTransform transform = CGAffineTransform.MakeIdentity(); CGRect bounds = new CGRect(0, 0, width, height); if (width > kMaxResolution || height > kMaxResolution) { float ratio = width / height; if (ratio > 1) { // bounds.Size = new CGSize (kMaxResolution, bounds.Size.Width / ratio); bounds.Size = new CGSize(kMaxResolution, kMaxResolution / ratio); } else { // bounds.Size = new CGSize (bounds.Size.Height * ratio, kMaxResolution); bounds.Size = new CGSize(kMaxResolution * ratio, kMaxResolution); } } float scaleRatio = (float)bounds.Size.Width / width; CGSize imageSize = new CGSize(imgRef.Width, imgRef.Height); float boundHeight; UIImageOrientation orient = image.Orientation; switch (orient) { case UIImageOrientation.Up: //EXIF = 1 transform = CGAffineTransform.MakeIdentity(); break; case UIImageOrientation.UpMirrored: //EXIF = 2 transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0.0f); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); break; case UIImageOrientation.Down: //EXIF = 3 transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height); transform = CGAffineTransform.Rotate(transform, (float)Math.PI); break; case UIImageOrientation.DownMirrored: //EXIF = 4 transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Height); transform = CGAffineTransform.Scale(transform, 1.0f, -1.0f); break; case UIImageOrientation.LeftMirrored: //EXIF = 5 boundHeight = (float)bounds.Size.Height; bounds.Size = new CGSize(boundHeight, (float)bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.Left: //EXIF = 6 boundHeight = (float)bounds.Size.Height; bounds.Size = new CGSize(boundHeight, (float)bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.RightMirrored: //EXIF = 7 boundHeight = (float)bounds.Size.Height; bounds.Size = new CGSize(boundHeight, (float)bounds.Size.Width); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; case UIImageOrientation.Right: //EXIF = 8 boundHeight = (float)bounds.Size.Height; bounds.Size = new CGSize(boundHeight, (float)bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; default: break; } UIGraphics.BeginImageContext(bounds.Size); using (CGContext context = UIGraphics.GetCurrentContext()) { if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left) { context.ScaleCTM(-scaleRatio, scaleRatio); context.TranslateCTM(-height, 0); } else { context.ScaleCTM(scaleRatio, -scaleRatio); context.TranslateCTM(0, -height); } context.ConcatCTM(transform); context.DrawImage(new CGRect(0, 0, width, height), imgRef); UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return(imageCopy); } } }
public void UpdateCell(Post post) { _currentPost = post; _scheduledWorkAvatar?.Cancel(); if (!string.IsNullOrEmpty(_currentPost.Avatar)) { _scheduledWorkAvatar = ImageService.Instance.LoadUrl(_currentPost.Avatar, TimeSpan.FromDays(30)) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .FadeAnimation(false, false, 0) .DownSample(200) .Into(avatar); } else { avatar.Image = UIImage.FromBundle("ic_noavatar"); } if (_currentPost.VoteChanging) { Animate(); } else { likeButton.Transform = CGAffineTransform.MakeScale(1f, 1f); likeButton.Selected = _currentPost.Vote; likeButton.Enabled = true; } commentText.Text = _currentPost.Body; loginLabel.Text = _currentPost.Author; //costLabel.Text = BaseViewController.ToFormatedCurrencyString(_currentPost.TotalPayoutReward); timestamp.Text = _currentPost.Created.ToPostTime(); likeLabel.Text = AppSettings.LocalizationManager.GetText(_currentPost.NetLikes == 1 ? LocalizationKeys.Like : LocalizationKeys.Likes, _currentPost.NetLikes); flagLabel.Text = AppSettings.LocalizationManager.GetText(_currentPost.NetFlags == 1 ? LocalizationKeys.Flag : LocalizationKeys.Flags, _currentPost.NetFlags); if (!_isInitialized) { avatar.Layer.CornerRadius = avatar.Frame.Size.Width / 2; var tap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); var costTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); var replyTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Reply, _currentPost); }); var likersTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Voters, _currentPost); }); var flagersTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Flagers, _currentPost); }); replyButton.AddGestureRecognizer(replyTap); profileTapView.AddGestureRecognizer(tap); costLabel.AddGestureRecognizer(costTap); likeLabel.AddGestureRecognizer(likersTap); flagLabel.AddGestureRecognizer(flagersTap); commentText.Font = Helpers.Constants.Regular14; loginLabel.Font = Helpers.Constants.Semibold14; likeLabel.Font = Helpers.Constants.Regular12; costLabel.Font = Helpers.Constants.Regular12; replyButton.Font = Helpers.Constants.Regular12; timestamp.Font = Helpers.Constants.Regular12; likeButton.TouchDown += LikeTap; RightSwipeSettings.Transition = MGSwipeTransition.Border; deleteButton = MGSwipeButton.ButtonWithTitle("", UIImage.FromBundle("ic_delete"), UIColor.FromRGB(250, 250, 250), 26, (tableCell) => { CellAction?.Invoke(ActionType.Delete, _currentPost); return(true); }); editButton = MGSwipeButton.ButtonWithTitle("", UIImage.FromBundle("ic_edit"), UIColor.FromRGB(250, 250, 250), 26, (arg0) => { CellAction?.Invoke(ActionType.Edit, _currentPost); return(true); }); flagButton = MGSwipeButton.ButtonWithTitle("", UIImage.FromBundle("ic_flag"), UIColor.FromRGB(250, 250, 250), 26, (arg0) => { CellAction?.Invoke(ActionType.Flag, _currentPost); return(true); }); _isInitialized = true; if (!AppSettings.User.IsAuthenticated) { replyButton.Hidden = true; replyHiddenConstraint.Active = true; replyVisibleConstraint.Active = false; } } if (_currentPost.NetFlags > 0) { flagLabel.Hidden = false; flagVisibleConstraint.Active = true; flagHiddenConstraint.Active = false; } else { flagVisibleConstraint.Active = false; flagHiddenConstraint.Active = true; flagLabel.Hidden = true; } if (_currentPost.NetLikes > 0) { likeLabel.Hidden = false; flagVisibleConstraint.Active = true; likeHiddenConstraint.Active = false; } else { likeLabel.Hidden = true; flagVisibleConstraint.Active = false; likeHiddenConstraint.Active = true; } var rightButtons = new List <MGSwipeButton>(); if (_currentPost.Author != AppSettings.User.Login) { rightButtons.Add(flagButton); } else if (_currentPost.CashoutTime > DateTime.Now) { rightButtons.Insert(0, deleteButton); //rightButtons.Insert(1, editButton); } RightButtons = rightButtons.ToArray(); }
private void UpdateViewFrames(bool animated = false) { var center = CalculateCenter(_targetView, _containerView); if (_targetView != null) { _targetRippleView.Bounds = new CGRect(x: 0, y: 0, width: _targetView.Bounds.Width + TargetHolderRadius, height: _targetView.Bounds.Height + TargetHolderRadius); _targetRippleView.Center = center; } if (_targetHolderView != null && _targetRippleView != null) { _targetHolderView.Bounds = new CGRect(x: 0, y: 0, width: _targetRippleView.Bounds.Width, height: _targetRippleView.Bounds.Height); _targetHolderView.Center = center; } if (_hiddenTargetHolderView != null && _targetHolderView != null) { _hiddenTargetHolderView.Frame = _targetHolderView.Frame; } if (_targetCopyView != null) { var targetCopyViewWidth = _targetCopyView.Frame.Width; var targetCopyViewHeight = _targetCopyView.Frame.Height; _targetCopyView.Bounds = new CGRect(x: 0, y: 0, width: targetCopyViewWidth, height: targetCopyViewHeight); _targetCopyView.Center = center; } if (_instructionView != null) { nfloat yPosition = 0; nfloat instructionViewWidth = 0; nfloat instructionViewHeight = 0; var safeAreaInsets = new UIEdgeInsets(); if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { safeAreaInsets = SafeAreaInsets; } Console.WriteLine( $"AddInstructionView {safeAreaInsets.Left}, {safeAreaInsets.Top}, {safeAreaInsets.Right}, {safeAreaInsets.Bottom}"); var xPosition = safeAreaInsets.Left; if (TargetShape == TargetShape.None) { yPosition = safeAreaInsets.Top; instructionViewHeight = _containerView.Frame.Height - safeAreaInsets.Top - safeAreaInsets.Bottom; } else if (_targetView != null) { if (GetTargetPosition(_targetView, _containerView) == TargetPosition.Above) { yPosition = center.Y + ((_targetView.Bounds.Height) * 0.5f) + TargetHolderRadius; instructionViewHeight = _containerView.Frame.Height - yPosition - safeAreaInsets.Top - safeAreaInsets.Bottom; } else { yPosition = safeAreaInsets.Top; //center.Y - TEXT_CENTER_OFFSET - LABEL_DEFAULT_HEIGHT * 2; instructionViewHeight = center.Y - (_targetView.Bounds.Height * 0.5f) - safeAreaInsets.Top; } } instructionViewWidth = _containerView.Frame.Width - safeAreaInsets.Left - safeAreaInsets.Right; // - (LABEL_MARGIN + LABEL_MARGIN); _instructionView.Frame = new CGRect(x: xPosition, y: yPosition, width: instructionViewWidth, height: instructionViewHeight); _instructionView.LayoutIfNeeded(); } if (_backgroundView != null) { switch (BackgroundViewType) { case BackgroundTypeStyle.Full: _backgroundView.Frame = new CGRect(x: 0, y: 0, width: UIScreen.MainScreen.Bounds.Width, height: UIScreen.MainScreen.Bounds.Height); break; } AddBackgroundMask(TargetHolderRadius, _backgroundView); var scale = TARGET_HOLDER_RADIUS / (_backgroundView.Frame.Width / 2); _backgroundView.Transform = CGAffineTransform.MakeScale(scale, scale); // Initial set to support animation _backgroundView.Center = _targetHolderView.Center; } //TODO move this somewhere better if (!animated) { var frameCenter = Frame.Center(); _targetHolderView.Transform = CGAffineTransform.MakeIdentity(); //CGAffineTransform.MakeScale(1, 1); _targetHolderView.Center = frameCenter; _backgroundView.Transform = CGAffineTransform.MakeIdentity(); //CGAffineTransform.MakeScale(1, 1); _backgroundView.Center = frameCenter; } if (_tapView != null) { _tapView.Frame = Frame; } }
public CVPixelBuffer CroppedSampleBuffer(CMSampleBuffer sampleBuffer, CGSize targetSize) { var imageBuffer = sampleBuffer.GetImageBuffer(); if (imageBuffer == null) { throw new ArgumentException("Cannot convert to CVImageBuffer"); } // Only doing these calculations once for efficiency. // If the incoming images could change orientation or size during a session, this would need to be reset when that happens. if (!alreadySet) { alreadySet = true; var imageSize = imageBuffer.EncodedSize; var rotatedSize = new CGSize(imageSize.Height, imageSize.Width); if (targetSize.Width > rotatedSize.Width || targetSize.Height > rotatedSize.Height) { throw new NotSupportedException("Captured image is smaller than image size for model."); } var shorterSide = rotatedSize.Width < rotatedSize.Height ? rotatedSize.Width : rotatedSize.Height; rotateTransform = new CIAffineTransform { Transform = new CGAffineTransform(0, -1, 1, 0, 0, shorterSide) //Transform = CGAffineTransform.MakeIdentity() }; var scale = targetSize.Width / shorterSide; scaleTransform = new CIAffineTransform { Transform = CGAffineTransform.MakeScale(scale, scale), }; var xDiff = rotatedSize.Width * scale - targetSize.Width; var yDiff = rotatedSize.Height * scale - targetSize.Height; cropTransform = new CIAffineTransform { //Transform = CGAffineTransform.MakeTranslation(xDiff / 2.0f, yDiff / 2.0f), Transform = CGAffineTransform.MakeIdentity() }; } // Convert to CIImage because it is easier to manipulate var ciImage = CIImage.FromImageBuffer(imageBuffer); rotateTransform.Image = ciImage; scaleTransform.Image = rotateTransform.OutputImage; cropTransform.Image = scaleTransform.OutputImage; var cropped = cropTransform.OutputImage; // Note that the above pipeline could be easily appended with other image manipulations. // For example, to change the image contrast. It would be most efficient to handle all of // the image manipulation in a single Core Image pipeline because it can be hardware optimized. // Only need to create this buffer one time and then we can reuse it for every frame if (resultBuffer == null || resultBuffer.Handle == IntPtr.Zero) { byte[] data = new byte[(int)targetSize.Height * 4 * (int)targetSize.Width]; resultBuffer = CVPixelBuffer.Create((nint)targetSize.Width, (nint)targetSize.Height, CVPixelFormatType.CV32BGRA, data, 4 * (nint)targetSize.Width, null); // HACK if (resultBuffer == null) { throw new Exception("Can't allocate pixel buffer."); } } context.Render(cropped, resultBuffer); // For debugging //var image = ImageBufferToUIImage(resultBuffer); //Console.WriteLine("Image size: " + image.Size); // set breakpoint to see image being provided to CoreML return(resultBuffer); }
UIImage ChangeOrientation(UIImage rotatedImage) { float width = rotatedImage.CGImage.Width; float height = rotatedImage.CGImage.Height; CGImage imgRef = rotatedImage.CGImage; CGAffineTransform transform = CGAffineTransform.MakeIdentity(); CGRect bounds = new CGRect(0, 0, width, height); float scaleRatio = (float)(bounds.Size.Width / width); CGSize imageSize = new CGSize(imgRef.Width, imgRef.Height); var orient = rotatedImage.Orientation; switch (orient) { case UIImageOrientation.Right: bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0)); break; case UIImageOrientation.Up: //EXIF = 1 transform = CGAffineTransform.MakeIdentity(); break; case UIImageOrientation.UpMirrored: //EXIF = 2 transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0.0f); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); break; case UIImageOrientation.Down: //EXIF = 3 transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height); transform = CGAffineTransform.Rotate(transform, (System.nfloat)Math.PI); break; case UIImageOrientation.DownMirrored: //EXIF = 4 transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Height); transform = CGAffineTransform.Scale(transform, 1.0f, -1.0f); break; case UIImageOrientation.LeftMirrored: //EXIF = 5 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width); transform = CGAffineTransform.Scale(transform, -1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0)); break; case UIImageOrientation.Left: //EXIF = 6 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(3.0 * Math.PI / 2.0)); break; case UIImageOrientation.RightMirrored: //EXIF = 7 bounds.Size = new CGSize(bounds.Size.Height, bounds.Size.Width); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (System.nfloat)(Math.PI / 2.0)); break; } UIGraphics.BeginImageContext(bounds.Size); CGContext context = UIGraphics.GetCurrentContext(); if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left) { context.ScaleCTM(-scaleRatio, scaleRatio); context.TranslateCTM(-height, 0); } else { context.ScaleCTM(scaleRatio, -scaleRatio); context.TranslateCTM(0, -height); } context.ConcatCTM(transform); context.DrawImage(new CGRect(0, 0, width, height), imgRef); UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); NSData str = imageCopy.AsPNG(); return(imageCopy); }
private void InitWithCGImage(CGImage image, All filter) { int width, height, i; CGContext context = null; IntPtr data; CGColorSpace colorSpace; IntPtr tempData; bool hasAlpha; CGImageAlphaInfo info; CGAffineTransform transform; Size imageSize; SurfaceFormat pixelFormat; bool sizeToFit = false; if (image == null) { throw new ArgumentException(" NSImage is invalid! "); } info = image.AlphaInfo; hasAlpha = ((info == CGImageAlphaInfo.PremultipliedLast) || (info == CGImageAlphaInfo.PremultipliedFirst) || (info == CGImageAlphaInfo.Last) || (info == CGImageAlphaInfo.First) ? true : false); if (image.ColorSpace != null) { if (hasAlpha) { pixelFormat = SurfaceFormat.Rgba32; } else { pixelFormat = SurfaceFormat.Rgb32; } } else { pixelFormat = SurfaceFormat.Alpha8; } imageSize = new Size(image.Width, image.Height); transform = CGAffineTransform.MakeIdentity(); width = imageSize.Width; if ((width != 1) && ((width & (width - 1)) != 0)) { i = 1; while ((sizeToFit ? 2 * i : i) < width) { i *= 2; } width = i; } height = imageSize.Height; if ((height != 1) && ((height & (height - 1)) != 0)) { i = 1; while ((sizeToFit ? 2 * i : i) < height) { i *= 2; } height = i; } // TODO: kMaxTextureSize = 1024 while ((width > 1024) || (height > 1024)) { width /= 2; height /= 2; transform = CGAffineTransform.MakeScale(0.5f, 0.5f); imageSize.Width /= 2; imageSize.Height /= 2; } switch (pixelFormat) { case SurfaceFormat.Rgba32: colorSpace = CGColorSpace.CreateDeviceRGB(); data = Marshal.AllocHGlobal(height * width * 4); context = new CGBitmapContext(data, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.PremultipliedLast); colorSpace.Dispose(); break; case SurfaceFormat.Rgb32: colorSpace = CGColorSpace.CreateDeviceRGB(); data = Marshal.AllocHGlobal(height * width * 4); context = new CGBitmapContext(data, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.NoneSkipLast); colorSpace.Dispose(); break; case SurfaceFormat.Alpha8: data = Marshal.AllocHGlobal(height * width); context = new CGBitmapContext(data, width, height, 8, width, null, CGImageAlphaInfo.Only); break; default: throw new NotSupportedException("Invalid pixel format"); } context.ClearRect(new RectangleF(0, 0, width, height)); context.TranslateCTM(0, height - imageSize.Height); if (!transform.IsIdentity) { context.ConcatCTM(transform); } context.DrawImage(new RectangleF(0, 0, image.Width, image.Height), image); //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" if (pixelFormat == SurfaceFormat.Rgb32) { tempData = Marshal.AllocHGlobal(height * width * 2); int d32; short d16; int inPixel32Count = 0, outPixel16Count = 0; for (i = 0; i < width * height; ++i, inPixel32Count += sizeof(int)) { d32 = Marshal.ReadInt32(data, inPixel32Count); short R = (short)((((d32 >> 0) & 0xFF) >> 3) << 11); short G = (short)((((d32 >> 8) & 0xFF) >> 2) << 5); short B = (short)((((d32 >> 16) & 0xFF) >> 3) << 0); d16 = (short)(R | G | B); Marshal.WriteInt16(tempData, outPixel16Count, d16); outPixel16Count += sizeof(short); } Marshal.FreeHGlobal(data); data = tempData; } InitWithData(data, pixelFormat, width, height, imageSize, filter); context.Dispose(); Marshal.FreeHGlobal(data); }
public static void Resize(this UISwitch self) { var scale = switchHeight / self.Frame.Height; self.Transform = CGAffineTransform.MakeScale(scale, scale); }
// rect changes depending on if the whole view is being redrawn, or just a section public override void Draw(CGRect rect) { Console.WriteLine("Draw() Called"); base.Draw(rect); // get a reference to the context using (CGContext context = UIGraphics.GetCurrentContext()) { // declare vars int remainder; int textHeight = 20; // invert the 'y' coordinates on the text context.TextMatrix = CGAffineTransform.MakeScale(1, -1); #region -= vertical ticks =- // create our vertical tick lines using (CGLayer verticalTickLayer = CGLayer.Create(context, new CGSize(20, 3))) { // draw a single tick verticalTickLayer.Context.FillRect(new CGRect(0, 1, 20, 2)); // draw a vertical tick every 20 pixels float yPos = 20; int numberOfVerticalTicks = (((int)Frame.Height / 20) - 1); for (int i = 0; i < numberOfVerticalTicks; i++) { // draw the layer context.DrawLayer(verticalTickLayer, new CGPoint(0, yPos)); // starting at 40, draw the coordinate text nearly to the top if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points Math.DivRem((int)yPos, (int)80, out remainder); if (remainder == 0) { ShowTextAtPoint(context, 30, (yPos - (textHeight / 2)), yPos.ToString(), textHeight); } } // increment the position of the next tick yPos += 20; } } #endregion #region -= horizontal ticks =- // create our horizontal tick lines using (CGLayer horizontalTickLayer = CGLayer.Create(context, new CGSize(3, 20))) { horizontalTickLayer.Context.FillRect(new CGRect(1, 0, 2, 20)); // draw a horizontal tick every 20 pixels float xPos = 20; int numberOfHorizontalTicks = (((int)Frame.Width / 20) - 1); for (int i = 0; i < numberOfHorizontalTicks; i++) { context.DrawLayer(horizontalTickLayer, new CGPoint(xPos, 0)); // starting at 100, draw the coordinate text nearly to the top if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points Math.DivRem((int)xPos, (int)80, out remainder); if (remainder == 0) { ShowCenteredTextAtPoint(context, xPos, 40, xPos.ToString(), textHeight); } } // increment the position of the next tick xPos += 20; } } #endregion // draw our "origin" text ShowTextAtPoint(context, 20, (30 + (textHeight / 2)), "Origin (0,0)", textHeight); #region -= points =- // (250,700) context.FillEllipseInRect(new CGRect(250, 700, 6, 6)); ShowCenteredTextAtPoint(context, 250, 695, "(250,700)", textHeight); // (500,300) context.FillEllipseInRect(new CGRect(500, 300, 6, 6)); ShowCenteredTextAtPoint(context, 500, 295, "(500,300)", textHeight); #endregion } }
public void ScaleTransform(float scaleX, float scaleY) { Control.ScaleCTM(scaleX, scaleY); currentTransform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(scaleX, scaleY), currentTransform); }
public nfloat UpdateCell(Post post, CellSizeHelper variables) { _currentPost = post; likesMargin = leftMargin; _avatarImage?.RemoveFromSuperview(); _avatarImage = new UIImageView(new CGRect(leftMargin, 20, 30, 30)); _avatarImage.Layer.CornerRadius = _avatarImage.Frame.Size.Width / 2; _avatarImage.ClipsToBounds = true; _avatarImage.ContentMode = UIViewContentMode.ScaleAspectFill; _contentView.AddSubview(_avatarImage); _scheduledWorkAvatar?.Cancel(); if (!string.IsNullOrEmpty(_currentPost.Avatar)) { _scheduledWorkAvatar = ImageService.Instance.LoadUrl(_currentPost.Avatar, TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .FadeAnimation(false) .DownSample(200) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Normal) .Into(_avatarImage); } else { _avatarImage.Image = UIImage.FromBundle("ic_noavatar"); } _author.Text = _currentPost.Author; _timestamp.Text = _currentPost.Created.ToPostTime(); _photoScroll.Frame = new CGRect(0, _avatarImage.Frame.Bottom + 20, UIScreen.MainScreen.Bounds.Width, variables.PhotoHeight); _photoScroll.ContentSize = new CGSize(UIScreen.MainScreen.Bounds.Width * _currentPost.Media.Length, variables.PhotoHeight); foreach (var subview in _photoScroll.Subviews) { subview.RemoveFromSuperview(); } for (int i = 0; i < _scheduledWorkBody.Length; i++) { _scheduledWorkBody[i]?.Cancel(); } _scheduledWorkBody = new IScheduledWork[_currentPost.Media.Length]; _bodyImage = new UIImageView[_currentPost.Media.Length]; for (int i = 0; i < _currentPost.Media.Length; i++) { _bodyImage[i] = new UIImageView(); _bodyImage[i].ClipsToBounds = true; _bodyImage[i].UserInteractionEnabled = true; _bodyImage[i].ContentMode = UIViewContentMode.ScaleAspectFill; _bodyImage[i].Frame = new CGRect(UIScreen.MainScreen.Bounds.Width * i, 0, UIScreen.MainScreen.Bounds.Width, variables.PhotoHeight); _photoScroll.AddSubview(_bodyImage[i]); _scheduledWorkBody[i] = ImageService.Instance.LoadUrl(_currentPost.Media[i].Url) .Retry(2) .FadeAnimation(false) .WithCache(FFImageLoading.Cache.CacheType.All) .WithPriority(LoadingPriority.Highest) /* .DownloadProgress((f)=> * { * })*/ .Into(_bodyImage[i]); } if (_currentPost.TopLikersAvatars.Any() && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[0])) { _firstLikerImage?.RemoveFromSuperview(); _firstLikerImage = new UIImageView(); _contentView.AddSubview(_firstLikerImage); _firstLikerImage.Layer.CornerRadius = likersCornerRadius; _firstLikerImage.ClipsToBounds = true; _firstLikerImage.ContentMode = UIViewContentMode.ScaleAspectFill; _firstLikerImage.Frame = new CGRect(leftMargin, _photoScroll.Frame.Bottom + likersY, likersImageSide, likersImageSide); _scheduledWorkfirst?.Cancel(); _scheduledWorkfirst = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[0], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .DownSample(width: 100) .FadeAnimation(false) .WithPriority(LoadingPriority.Lowest) .Into(_firstLikerImage); likesMargin = _firstLikerImage.Frame.Right + likesMarginConst; } else if (_firstLikerImage != null) { _firstLikerImage.Hidden = true; } if (_currentPost.TopLikersAvatars.Count() >= 2 && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[1])) { _secondLikerImage?.RemoveFromSuperview(); _secondLikerImage = new UIImageView(); _contentView.AddSubview(_secondLikerImage); _secondLikerImage.Layer.CornerRadius = likersCornerRadius; _secondLikerImage.ClipsToBounds = true; _secondLikerImage.ContentMode = UIViewContentMode.ScaleAspectFill; _secondLikerImage.Frame = new CGRect(_firstLikerImage.Frame.Right - likersMargin, _photoScroll.Frame.Bottom + likersY, likersImageSide, likersImageSide); _scheduledWorksecond?.Cancel(); _scheduledWorksecond = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[1], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Lowest) .DownSample(width: 100) .FadeAnimation(false) .Into(_secondLikerImage); likesMargin = _secondLikerImage.Frame.Right + likesMarginConst; } else if (_secondLikerImage != null) { _secondLikerImage.Hidden = true; } if (_currentPost.TopLikersAvatars.Count() >= 3 && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[2])) { _thirdLikerImage?.RemoveFromSuperview(); _thirdLikerImage = new UIImageView(); _contentView.AddSubview(_thirdLikerImage); _thirdLikerImage.Layer.CornerRadius = likersCornerRadius; _thirdLikerImage.ClipsToBounds = true; _thirdLikerImage.ContentMode = UIViewContentMode.ScaleAspectFill; _thirdLikerImage.Frame = new CGRect(_secondLikerImage.Frame.Right - likersMargin, _photoScroll.Frame.Bottom + likersY, likersImageSide, likersImageSide); _scheduledWorkthird?.Cancel(); _scheduledWorkthird = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[2], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Lowest) .DownSample(width: 100) .FadeAnimation(false) .Into(_thirdLikerImage); likesMargin = _thirdLikerImage.Frame.Right + likesMarginConst; } else if (_thirdLikerImage != null) { _thirdLikerImage.Hidden = true; } nfloat flagMargin = 0; if (_currentPost.NetLikes != 0) { _likes.Text = AppSettings.LocalizationManager.GetText(LocalizationKeys.Likes, _currentPost.NetLikes); var likesWidth = _likes.SizeThatFits(new CGSize(0, underPhotoPanelHeight)); _likes.Frame = new CGRect(likesMargin, _photoScroll.Frame.Bottom, likesWidth.Width, underPhotoPanelHeight); flagMargin = flagsMarginConst; } else { _likes.Frame = new CGRect(likesMargin, _photoScroll.Frame.Bottom, 0, 0); } _likersTapView.Frame = new CGRect(leftMargin, _photoScroll.Frame.Bottom, _likes.Frame.Right - leftMargin, _likes.Frame.Height); if (_currentPost.NetFlags != 0) { _flags.Text = AppSettings.LocalizationManager.GetText(LocalizationKeys.Flags, _currentPost.NetFlags); var flagsWidth = _flags.SizeThatFits(new CGSize(0, underPhotoPanelHeight)); _flags.Frame = new CGRect(likesMargin + _likes.Frame.Width + flagMargin, _photoScroll.Frame.Bottom, flagsWidth.Width, underPhotoPanelHeight); } else { _flags.Frame = new CGRect(likesMargin, _photoScroll.Frame.Bottom, 0, 0); } _like.Frame = new CGRect(_contentView.Frame.Width - likeButtonWidthConst, _photoScroll.Frame.Bottom, likeButtonWidthConst, underPhotoPanelHeight); _like.Transform = CGAffineTransform.MakeScale(1f, 1f); if (_currentPost.VoteChanging) { Animate(); } else { _like.Layer.RemoveAllAnimations(); _like.LayoutIfNeeded(); _like.Image = _currentPost.Vote ? UIImage.FromBundle("ic_like_active") : UIImage.FromBundle("ic_like"); _like.UserInteractionEnabled = true; } _verticalSeparator.Frame = new CGRect(_contentView.Frame.Width - likeButtonWidthConst - 1, _photoScroll.Frame.Bottom + underPhotoPanelHeight / 2 - verticalSeparatorHeight / 2, 1, verticalSeparatorHeight); /* * _rewards.Text = BaseViewController.ToFormatedCurrencyString(_currentPost.TotalPayoutReward); * var rewardWidth = _rewards.SizeThatFits(new CGSize(0, underPhotoPanelHeight)); * _rewards.Frame = new CGRect(_verticalSeparator.Frame.Left - rewardWidth.Width, _photoScroll.Frame.Bottom, rewardWidth.Width, underPhotoPanelHeight); */ _topSeparator.Frame = new CGRect(0, _photoScroll.Frame.Bottom + underPhotoPanelHeight, UIScreen.MainScreen.Bounds.Width, 1); _attributedLabel.SetText(variables.Text); _attributedLabel.Frame = new CGRect(new CGPoint(leftMargin, _topSeparator.Frame.Bottom + 15), new CGSize(UIScreen.MainScreen.Bounds.Width - leftMargin * 2, variables.TextHeight)); _comments.Text = _currentPost.Children == 0 ? AppSettings.LocalizationManager.GetText(LocalizationKeys.PostFirstComment) : AppSettings.LocalizationManager.GetText(LocalizationKeys.ViewComments, _currentPost.Children); _comments.Frame = new CGRect(leftMargin - 5, _attributedLabel.Frame.Bottom + 5, _comments.SizeThatFits(new CGSize(10, 20)).Width + 10, 20 + 10); _bottomSeparator.Frame = new CGRect(0, _comments.Frame.Bottom + 10, UIScreen.MainScreen.Bounds.Width, 1); return(_bottomSeparator.Frame.Bottom); //for constant size checking //var constantsSize = _bottomSeparator.Frame.Bottom - _attributedLabel.Frame.Height - _bodyImage.Frame.Height; }
async Task DoUpdateView(bool force, int delay = 0) { UserInteractionEnabled = false; if (ViewModel == null) { return; } ArrowView.Hidden = string.IsNullOrWhiteSpace(viewModel.Text) || !viewModel.MarkerVisible; if (ColorPalette != null && viewModel.Fixed) { var colorIndex = viewModel.PaletteIndex % ColorPalette.Count; MarkerColor = ColorPalette[colorIndex]; } ShowHighlight = viewModel.TouchState == TouchState.Touching; var newShowMarker = viewModel.MarkerVisible; if ((ShowMarker != newShowMarker) || force) { //animation?.Stop(); if (force) { if (!ViewModel.Fixed) { MarkerColor = DefaultMarkerColor; } } if (!newShowMarker) { markerView.Alpha = 1; markerView.Transform = CGAffineTransform.MakeScale(1f, 1f); await AnimateAsync(0.3, () => { markerView.Alpha = 0; markerView.Transform = CGAffineTransform.MakeScale(1.5f, 1.5f); }); //animation = markerView // .CreateAnimator<TakingOffAnimator>() // .SetStartDelay(delay) // .SetDuration(300); //await animation.Animate(); //animation = null; ShowMarker = newShowMarker; } else { markerView.Alpha = 0; markerView.Transform = CGAffineTransform.MakeScale(1.5f, 1.5f); ShowMarker = newShowMarker; //animation = markerView.CreateAnimator<LandingAnimator>(); //await animation.Animate(); //animation = null; await AnimateAsync(0.3, () => { markerView.Alpha = 1; markerView.Transform = CGAffineTransform.MakeScale(1.0f, 1.0f); }); } } }
/// <summary> /// 不设置PreferredBackBuffer宽度和高度使用此方法 /// </summary> /// <param name="sourceResolution">源分辨率</param> /// <param name="destinationResolution">目标分辨率,通常设置设备实际分辨率</param> public static void FinishedLaunching(CGSize sourceResolution, CGSize destinationResolution) { //原游戏界面尺寸大小 float viewWidth = (float)sourceResolution.Width; float viewHeight = (float)sourceResolution.Height; //设备实际分辨率尺寸 float screenWidth = (float)destinationResolution.Width; float screenHeight = (float)destinationResolution.Height; //计算需要放大的倍数X方向,y方向 float scaleXValue = screenWidth / viewWidth; float scaleYValue = screenHeight / viewHeight; UIApplication.SharedApplication.Windows[0].RootViewController.View.Transform = CGAffineTransform.MakeScale(scaleXValue, scaleYValue); //如果界面存在偏移,可用一下方法移动视图位置 UIApplication.SharedApplication.Windows[0].RootViewController.View.Frame = new CGRect(0, 0, (int)screenWidth, (int)screenHeight); }
public static CGPath ToCGPath( this PathF target) { var path = new CGPath(); int pointIndex = 0; int arcAngleIndex = 0; int arcClockwiseIndex = 0; foreach (var operation in target.PathOperations) { if (operation == PathOperation.MoveTo) { var point = target[pointIndex++]; path.MoveToPoint(point.X, point.Y); } else if (operation == PathOperation.Line) { var endPoint = target[pointIndex++]; path.AddLineToPoint(endPoint.X, endPoint.Y); } else if (operation == PathOperation.Quad) { var controlPoint = target[pointIndex++]; var endPoint = target[pointIndex++]; path.AddQuadCurveToPoint( controlPoint.X, controlPoint.Y, endPoint.X, endPoint.Y); } else if (operation == PathOperation.Cubic) { var controlPoint1 = target[pointIndex++]; var controlPoint2 = target[pointIndex++]; var endPoint = target[pointIndex++]; path.AddCurveToPoint( controlPoint1.X, controlPoint1.Y, controlPoint2.X, controlPoint2.Y, endPoint.X, endPoint.Y); } else if (operation == PathOperation.Arc) { var topLeft = target[pointIndex++]; var bottomRight = target[pointIndex++]; float startAngle = target.GetArcAngle(arcAngleIndex++); float endAngle = target.GetArcAngle(arcAngleIndex++); var clockwise = target.IsArcClockwise(arcClockwiseIndex++); var startAngleInRadians = GraphicsOperations.DegreesToRadians(-startAngle); var endAngleInRadians = GraphicsOperations.DegreesToRadians(-endAngle); while (startAngleInRadians < 0) { startAngleInRadians += (float)Math.PI * 2; } while (endAngleInRadians < 0) { endAngleInRadians += (float)Math.PI * 2; } var cx = (bottomRight.X + topLeft.X) / 2; var cy = (bottomRight.Y + topLeft.Y) / 2; var width = bottomRight.X - topLeft.X; var height = bottomRight.Y - topLeft.Y; var r = width / 2; var transform = CGAffineTransform.MakeTranslation(cx, cy); transform = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(1, height / width), transform); path.AddArc(transform, 0, 0, r, startAngleInRadians, endAngleInRadians, !clockwise); } else if (operation == PathOperation.Close) { path.CloseSubpath(); } } return(path); }
protected override void HandleLongPressGesture() { switch (LongPressGestureRecognizer.State) { case UIGestureRecognizerState.Began: { // we try to grab the current seelected item and draw a floating copy of it on the Drag Surface // the copy is just an image of it using RasterizedImage var currentIndexPath = CollectionView.IndexPathForItemAtPoint(LongPressGestureRecognizer.LocationInView(CollectionView)); SelectedItemIndexPath = currentIndexPath; if (SelectedItemIndexPath == null) { return; } if (!DataSource.CanMoveItemAtIndexPath(SelectedItemIndexPath)) { return; } var collectionViewCell = CollectionView.CellForItem(SelectedItemIndexPath); var tpoint = DragSurface.ConvertPointFromView(collectionViewCell.Frame.Location, CollectionView); RectangleF frame = new RectangleF(tpoint.X, tpoint.Y, collectionViewCell.Frame.Size.Width, collectionViewCell.Frame.Size.Height); CurrentView = new UIView(frame); collectionViewCell.Highlighted = true; var highlightedImageView = new UIImageView(RastertizedImage(collectionViewCell)); highlightedImageView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; highlightedImageView.Alpha = 1.0f; collectionViewCell.Highlighted = false; var imageView = new UIImageView(RastertizedImage(collectionViewCell)); imageView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; imageView.Alpha = 0.0f; CurrentView.AddSubview(imageView); CurrentView.AddSubview(highlightedImageView); DragSurface.AddSubview(CurrentView); // add this to the top level view so that we can drag outside CurrentViewCenter = CurrentView.Center; OnWillBeginDraggingItem(SelectedItemIndexPath); // we animate the drawing out of the floating copy UIView.Animate(0.3, 0.0, UIViewAnimationOptions.BeginFromCurrentState, () => { CurrentView.Transform = CGAffineTransform.MakeScale(1.1f, 1.1f); highlightedImageView.Alpha = 0.0f; imageView.Alpha = 1.0f; }, () => { highlightedImageView.RemoveFromSuperview(); OnDidBegingDraggingItem(SelectedItemIndexPath); }); InvalidateLayout(); } break; case UIGestureRecognizerState.Cancelled: case UIGestureRecognizerState.Ended: { var currentIndexPath = SelectedItemIndexPath; if (currentIndexPath == null || CurrentView == null) { return; } SelectedItemIndexPath = null; CurrentViewCenter = PointF.Empty; OnWillEndDraggingItem(currentIndexPath); UIView.Animate(0.3, 0.0, UIViewAnimationOptions.BeginFromCurrentState, () => { var layoutAttributes = this.LayoutAttributesForItem(currentIndexPath); CurrentView.Transform = CGAffineTransform.MakeScale(1.0f, 1.0f); CurrentView.Center = CollectionView.ConvertPointToView(layoutAttributes.Center, DragSurface); }, () => { CurrentView.RemoveFromSuperview(); CurrentView = null; InvalidateLayout(); OnDidEndDraggingItem(currentIndexPath); }); } break; } }
public override void ViewDidLoad() { base.ViewDidLoad(); InitElements(); var circleLayer = new CAShapeLayer(); var circlePath = UIBezierPath.FromRect(cadreIV.Frame); circlePath.UsesEvenOddFillRule = true; circleLayer.Path = circlePath.CGPath; var maskPath = UIBezierPath.FromRect(new CGRect(0, (int)headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2, View.Frame.Width, (int)(View.Frame.Height - (headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2 + View.Frame.Width / 8)))); maskPath.AppendPath(circlePath); maskPath.UsesEvenOddFillRule = true; fillLayer.Path = maskPath.CGPath; fillLayer.FillRule = CAShapeLayer.FillRuleEvenOdd; fillLayer.FillColor = maskColor.CGColor; View.Layer.AddSublayer(fillLayer); nfloat width_height_ratio; int image_height, image_width; if (imageView.Image.Size.Height > imageView.Image.Size.Width) { width_height_ratio = imageView.Image.Size.Height / imageView.Image.Size.Width; image_width = (int)View.Frame.Width; image_height = (int)(image_width * width_height_ratio); imageView.Frame = new Rectangle(0, (int)(headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2), image_width, image_height); } else if (imageView.Image.Size.Height < imageView.Image.Size.Width) { width_height_ratio = imageView.Image.Size.Width / imageView.Image.Size.Height; image_width = (int)View.Frame.Width; image_height = (int)(image_width / width_height_ratio); imageView.Frame = new Rectangle(0, (int)(headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2), image_width, image_height); } else if (imageView.Image.Size.Height == imageView.Image.Size.Width) { image_width = (int)View.Frame.Width; image_height = image_width; imageView.Frame = new Rectangle(0, (int)(headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2), image_width, image_height); } backBn.TouchUpInside += (s, e) => { if (came_from_adding) { RemoveImage(null, null); } else { this.NavigationController.PopViewController(true); } }; pinchGesture = new UIPinchGestureRecognizer(() => { if (pinchGesture.State == UIGestureRecognizerState.Began || pinchGesture.State == UIGestureRecognizerState.Changed) { if (cadreIV.Frame.X > 0 && cadreIV.Frame.Y > (int)(headerView.Frame.Y + headerView.Frame.Height) && cadreIV.Frame.X + cadreIV.Frame.Width < View.Frame.Width && cadreIV.Frame.Y + cadreIV.Frame.Height < (imageView.Frame.Height + imageView.Frame.Y)) { pinchGesture.View.Transform *= CGAffineTransform.MakeScale(pinchGesture.Scale, pinchGesture.Scale); pinchGesture.Scale = 1; circleLayer = new CAShapeLayer(); circlePath = UIBezierPath.FromRect(cadreIV.Frame); circlePath.UsesEvenOddFillRule = true; circleLayer.Path = circlePath.CGPath; maskPath = UIBezierPath.FromRect(new CGRect(0, (int)headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2, View.Frame.Width, (int)(View.Frame.Height - (headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2 + View.Frame.Width / 8)))); maskPath.AppendPath(circlePath); maskPath.UsesEvenOddFillRule = true; fillLayer.Path = maskPath.CGPath; fillLayer.FillRule = CAShapeLayer.FillRuleEvenOdd; View.Layer.AddSublayer(fillLayer); } else { if (pinchGesture.Scale < 1) { pinchGesture.View.Transform *= CGAffineTransform.MakeScale(pinchGesture.Scale, pinchGesture.Scale); pinchGesture.Scale = 1; circleLayer = new CAShapeLayer(); circlePath = UIBezierPath.FromRect(cadreIV.Frame); circlePath.UsesEvenOddFillRule = true; circleLayer.Path = circlePath.CGPath; maskPath = UIBezierPath.FromRect(new CGRect(0, (int)headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2, View.Frame.Width, (int)(View.Frame.Height - (headerView.Frame.Y + headerView.Frame.Height + headerView.Frame.Height / 2 + View.Frame.Width / 8)))); maskPath.AppendPath(circlePath); maskPath.UsesEvenOddFillRule = true; fillLayer.Path = maskPath.CGPath; fillLayer.FillRule = CAShapeLayer.FillRuleEvenOdd; View.Layer.AddSublayer(fillLayer); } } } }); cadreIV.AddGestureRecognizer(pinchGesture); UIStoryboard sb = UIStoryboard.FromName("Main", null); //CropGalleryViewController.currentImage = current_imgBn.CurrentImage; vc = sb.InstantiateViewController(nameof(PersonalDataViewControllerNew)); if (came_from == Constants.edit) { vc = sb.InstantiateViewController(nameof(EditPersonalDataViewControllerNew)); } readyBn.TouchUpInside += (s, e) => { x = cadreIV.Frame.X; y = cadreIV.Frame.Y; w = cadreIV.Frame.Width; h = cadreIV.Frame.Height; var wwww1 = (float)(imageView.Image.Size.Width / View.Frame.Width); var hhhh1 = (float)(imageView.Image.Size.Height / imageView.Frame.Height); var ppp = (float)(cadreIV.Frame.X * wwww1); var lll = (float)(cadreIV.Frame.Y * hhhh1 - imageView.Frame.Y * wwww1); var www = (float)(cadreIV.Frame.Width * wwww1); var hhh = (float)(cadreIV.Frame.Height * hhhh1); var cropped_result = CenterCrop(imageView.Image, new RectangleF(ppp, lll, www, hhh)); try { PersonalDataViewControllerNew.images_list.RemoveAt(PersonalDataViewControllerNew.current_img_id); } catch { } PersonalDataViewControllerNew.images_list.Insert(PersonalDataViewControllerNew.current_img_id, cropped_result); this.NavigationController.PushViewController(vc, true); var vc_list = this.NavigationController.ViewControllers.ToList(); vc_list.RemoveAt(vc_list.Count - 2); vc_list.RemoveAt(vc_list.Count - 2); this.NavigationController.ViewControllers = vc_list.ToArray(); }; cancelBn.TouchUpInside += (s, e) => { if (came_from_adding) { RemoveImage(null, null); } else { this.NavigationController.PopViewController(true); } }; remove_imageBn.TouchUpInside += new EventHandler(this.RemoveImage); readyBn.Font = UIFont.FromName(Constants.fira_sans, 17f); cancelBn.Font = UIFont.FromName(Constants.fira_sans, 17f); remove_imageBn.Font = UIFont.FromName(Constants.fira_sans, 17f); }
public override void UpdateCell(Post post) { _currentPost = post; avatarImage.Image = null; _scheduledWorkAvatar?.Cancel(); bodyImage.Image = null; _scheduledWorkBody?.Cancel(); var media = _currentPost.Media[0]; _scheduledWorkBody = ImageService.Instance.LoadUrl(media.Url, Helpers.Constants.ImageCacheDuration) //.Retry(5) .FadeAnimation(false) .WithCache(FFImageLoading.Cache.CacheType.All) .DownSample((int)UIScreen.MainScreen.Bounds.Width) .WithPriority(LoadingPriority.Highest) .Into(bodyImage); if (!string.IsNullOrEmpty(_currentPost.Avatar)) { _scheduledWorkAvatar = ImageService.Instance.LoadUrl(_currentPost.Avatar, TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .FadeAnimation(false) .DownSample(200) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Normal) .Into(avatarImage); } else { avatarImage.Image = UIImage.FromBundle("ic_noavatar"); } topLikers.Hidden = true; if (_currentPost.TopLikersAvatars.Count() >= 1 && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[0])) { _scheduledWorkfirst?.Cancel(); firstLiker.Image = null; topLikers.Hidden = false; firstLiker.Hidden = false; _scheduledWorkfirst = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[0], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .DownSample(width: 100) .WithPriority(LoadingPriority.Lowest) .Into(firstLiker); } else { firstLiker.Hidden = true; } if (_currentPost.TopLikersAvatars.Count() >= 2 && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[1])) { _scheduledWorksecond?.Cancel(); secondLiker.Image = null; secondLiker.Hidden = false; _scheduledWorksecond = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[1], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Lowest) .DownSample(width: 100) .Into(secondLiker); } else { secondLiker.Hidden = true; } if (_currentPost.TopLikersAvatars.Count() >= 3 && !string.IsNullOrEmpty(_currentPost.TopLikersAvatars[2])) { _scheduledWorkthird?.Cancel(); thirdLiker.Image = null; thirdLiker.Hidden = false; _scheduledWorkthird = ImageService.Instance.LoadUrl(_currentPost.TopLikersAvatars[2], TimeSpan.FromDays(30)) .WithCache(FFImageLoading.Cache.CacheType.All) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .WithPriority(LoadingPriority.Lowest) .DownSample(width: 100) .Into(thirdLiker); } else { thirdLiker.Hidden = true; } cellText.Text = _currentPost.Author; rewards.Hidden = !BasePresenter.User.IsNeedRewards; //rewards.Text = BaseViewController.ToFormatedCurrencyString(_currentPost.TotalPayoutReward); netVotes.Text = AppSettings.LocalizationManager.GetText(LocalizationKeys.Like, _currentPost.NetVotes); if (_currentPost.VoteChanging) { Animate(); } else { likeButton.Transform = CGAffineTransform.MakeScale(1f, 1f); likeButton.Selected = _currentPost.Vote; } flagButton.Selected = _currentPost.Flag; viewCommentText.Text = _currentPost.Children == 0 ? AppSettings.LocalizationManager.GetText(LocalizationKeys.PostFirstComment) : AppSettings.LocalizationManager.GetText(LocalizationKeys.ViewComments, _currentPost.Children); likeButton.Enabled = true; flagButton.Enabled = true; postTimeStamp.Text = _currentPost.Created.ToPostTime(); imageHeight.Constant = PhotoHeight.Get(media.Size); contentViewWidth.Constant = UIScreen.MainScreen.Bounds.Width; if (!_isButtonBinded) { cellText.Font = Helpers.Constants.Semibold14; postTimeStamp.Font = Helpers.Constants.Regular12; netVotes.Font = Helpers.Constants.Semibold14; rewards.Font = Helpers.Constants.Semibold14; viewCommentText.Font = Helpers.Constants.Regular14; avatarImage.Layer.CornerRadius = avatarImage.Frame.Size.Width / 2; firstLiker.Layer.CornerRadius = firstLiker.Frame.Size.Width / 2; secondLiker.Layer.CornerRadius = secondLiker.Frame.Size.Width / 2; thirdLiker.Layer.CornerRadius = thirdLiker.Frame.Size.Width / 2; attributedLabel = new TTTAttributedLabel(); attributedLabel.EnabledTextCheckingTypes = NSTextCheckingType.Link; var prop = new NSDictionary(); attributedLabel.LinkAttributes = prop; attributedLabel.ActiveLinkAttributes = prop; commentView.AddSubview(attributedLabel); attributedLabel.Font = Helpers.Constants.Regular14; attributedLabel.Lines = 0; attributedLabel.UserInteractionEnabled = true; attributedLabel.Enabled = true; attributedLabel.AutoPinEdgeToSuperviewEdge(ALEdge.Left, 15f); attributedLabel.AutoPinEdgeToSuperviewEdge(ALEdge.Right, 15f); attributedLabel.AutoPinEdgeToSuperviewEdge(ALEdge.Top, 15f); viewCommentText.AutoPinEdge(ALEdge.Top, ALEdge.Bottom, attributedLabel, 5f); attributedLabel.Delegate = new TTTAttributedLabelFeedDelegate(TagAction); UITapGestureRecognizer tap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Preview, _currentPost); }); bodyImage.AddGestureRecognizer(tap); UITapGestureRecognizer imageTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); UITapGestureRecognizer textTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); UITapGestureRecognizer moneyTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); avatarImage.AddGestureRecognizer(imageTap); cellText.AddGestureRecognizer(textTap); rewards.AddGestureRecognizer(moneyTap); UITapGestureRecognizer commentTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Comments, _currentPost); }); viewCommentText.AddGestureRecognizer(commentTap); UITapGestureRecognizer netVotesTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Voters, _currentPost); }); netVotes.AddGestureRecognizer(netVotesTap); flagButton.TouchDown += FlagButton_TouchDown; likeButton.TouchDown += LikeTap; _isButtonBinded = true; Debug.WriteLine("Cell created"); } var noLinkAttribute = new UIStringAttributes { Font = Helpers.Constants.Regular14, ForegroundColor = Helpers.Constants.R15G24B30, }; var at = new NSMutableAttributedString(); at.Append(new NSAttributedString(_currentPost.Title, noLinkAttribute)); if (!string.IsNullOrEmpty(_currentPost.Description)) { at.Append(new NSAttributedString(Environment.NewLine)); at.Append(new NSAttributedString(Environment.NewLine)); at.Append(new NSAttributedString(_currentPost.Description, noLinkAttribute)); } foreach (var tag in _currentPost.Tags) { if (tag == "steepshot") { continue; } var linkAttribute = new UIStringAttributes { Link = new NSUrl(tag), Font = Helpers.Constants.Regular14, ForegroundColor = Helpers.Constants.R231G72B0, }; at.Append(new NSAttributedString($" #{tag}", linkAttribute)); } attributedLabel.SetText(at); }
/// <summary> /// Scales the and rotate image view. /// </summary> /// <returns>The and rotate image view.</returns> /// <param name="imageIn">Image in.</param> /// <param name="orIn">Or in.</param> public static UIImage ScaleAndRotateImageView(UIImage imageIn, UIImageOrientation orIn) { float kMaxResolution = 1024; UIImage imageCopy = imageIn; try { CGImage imgRef = imageIn.CGImage; imageIn.Dispose(); imageIn = null; float width = imgRef.Width; float height = imgRef.Height; Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 29)); CGAffineTransform transform = CGAffineTransform.MakeIdentity(); RectangleF bounds = new RectangleF(0, 0, width, height); if (width > kMaxResolution || height > kMaxResolution) { float ratio = width / height; if (ratio > 1) { bounds.Width = kMaxResolution; bounds.Height = bounds.Width / ratio; } else { bounds.Height = kMaxResolution; bounds.Width = bounds.Height * ratio; } } float scaleRatio = bounds.Width / width; SizeF imageSize = new SizeF(width, height); UIImageOrientation orient = orIn; float boundHeight; Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 53)); switch (orient) { case UIImageOrientation.Up: //EXIF = 1 transform = CGAffineTransform.MakeIdentity(); break; case UIImageOrientation.UpMirrored: //EXIF = 2 transform = CGAffineTransform.MakeTranslation(imageSize.Width, 0f); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); break; case UIImageOrientation.Down: //EXIF = 3 transform = CGAffineTransform.MakeTranslation(imageSize.Width, imageSize.Height); transform = CGAffineTransform.Rotate(transform, (float)Math.PI); break; case UIImageOrientation.DownMirrored: //EXIF = 4 transform = CGAffineTransform.MakeTranslation(0f, imageSize.Height); transform = CGAffineTransform.MakeScale(1.0f, -1.0f); break; case UIImageOrientation.LeftMirrored: //EXIF = 5 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(imageSize.Height, imageSize.Width); transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.Left: //EXIF = 6 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(0.0f, imageSize.Width); transform = CGAffineTransform.Rotate(transform, 3.0f * (float)Math.PI / 2.0f); break; case UIImageOrientation.RightMirrored: //EXIF = 7 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeScale(-1.0f, 1.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; case UIImageOrientation.Right: //EXIF = 8 boundHeight = bounds.Height; bounds.Height = bounds.Width; bounds.Width = boundHeight; transform = CGAffineTransform.MakeTranslation(imageSize.Height, 0.0f); transform = CGAffineTransform.Rotate(transform, (float)Math.PI / 2.0f); break; default: //throw new Exception("Invalid image orientation"); Debug.WriteLine(string.Format("ScaleAndRotateImageView Invalid image orientation - line# {0}", 110)); break; } try { Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 115)); UIGraphics.BeginImageContext(bounds.Size); CGContext context = UIGraphics.GetCurrentContext(); if (orient == UIImageOrientation.Right || orient == UIImageOrientation.Left) { context.ScaleCTM(-scaleRatio, scaleRatio); context.TranslateCTM(-height, 0); } else { context.ScaleCTM(scaleRatio, -scaleRatio); context.TranslateCTM(0, -height); } Debug.WriteLine(string.Format("ScaleAndRotateImageView - line# {0}", 130)); context.ConcatCTM(transform); context.DrawImage(new RectangleF(0, 0, width, height), imgRef); // added context dispose - to free memory used by picture image imgRef.Dispose(); imgRef = null; imageCopy.Dispose(); imageCopy = null; imageCopy = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); // added context dispose - to free memory used by the graphics context context.Dispose(); context = null; imageIn = null; } catch (Exception ex) { Debug.WriteLine("Exception Occured in ScaleAndRotateImageView - line # 164 method due to " + ex.Message); } } catch (Exception ex) { Debug.WriteLine("Exception Occured in ScaleAndRotateImageView - line # 169 method due to " + ex.Message); } return(imageCopy); }
// https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_patterns/dq_patterns.html#//apple_ref/doc/uid/TP30001066-CH206-TPXREF101 internal override void Setup(Graphics graphics, bool fill) { // if this is the same as the last that was set then return if (graphics.LastBrush == this) { return; } // obtain our width and height so we can set the pattern rectangle float hatch_width = getHatchWidth(hatchStyle); float hatch_height = getHatchHeight(hatchStyle); //choose the pattern to be filled based on the currentPattern selected var patternSpace = CGColorSpace.CreatePattern(null); graphics.context.SetFillColorSpace(patternSpace); graphics.context.SetStrokeColorSpace(patternSpace); patternSpace.Dispose(); // Pattern default work variables var patternRect = new CGRect(HALF_PIXEL_X, HALF_PIXEL_Y, hatch_width + HALF_PIXEL_X, hatch_height + HALF_PIXEL_Y); var patternTransform = CGAffineTransform.MakeIdentity(); // Since all the patterns were developed with MonoMac on Mac OS the coordinate system is // defaulted to the lower left corner being 0,0 which means for MonoTouch and any view // that is flipped we need to flip it again. Yep should have thought about it to begin with // will look into changing it later if need be. #if MONOMAC if (graphics.isFlipped) { patternTransform = new CGAffineTransform(1, 0, 0, -1, 0, hatch_height); } #endif #if MONOTOUCH if (!graphics.isFlipped) { patternTransform = new CGAffineTransform(1, 0, 0, -1, 0, hatch_height); } #endif // DrawPattern callback which will be set depending on hatch style CGPattern.DrawPattern drawPattern; switch (hatchStyle) { case HatchStyle.Horizontal: case HatchStyle.LightHorizontal: case HatchStyle.NarrowHorizontal: case HatchStyle.DarkHorizontal: drawPattern = HatchHorizontal; break; case HatchStyle.Vertical: case HatchStyle.LightVertical: case HatchStyle.NarrowVertical: case HatchStyle.DarkVertical: patternTransform = CGAffineTransform.MakeRotation(90 * (float)Math.PI / 180); drawPattern = HatchHorizontal; break; case HatchStyle.ForwardDiagonal: case HatchStyle.LightDownwardDiagonal: case HatchStyle.DarkDownwardDiagonal: case HatchStyle.WideDownwardDiagonal: // We will flip the x-axis here patternTransform = CGAffineTransform.MakeScale(-1, 1); drawPattern = HatchUpwardDiagonal; break; case HatchStyle.BackwardDiagonal: case HatchStyle.LightUpwardDiagonal: case HatchStyle.DarkUpwardDiagonal: case HatchStyle.WideUpwardDiagonal: drawPattern = HatchUpwardDiagonal; break; case HatchStyle.LargeGrid: case HatchStyle.SmallGrid: case HatchStyle.DottedGrid: drawPattern = HatchGrid; break; case HatchStyle.DiagonalCross: drawPattern = HatchDiagonalCross; break; case HatchStyle.Percent05: case HatchStyle.Percent10: case HatchStyle.Percent20: case HatchStyle.Percent25: case HatchStyle.Percent30: case HatchStyle.Percent40: case HatchStyle.Percent50: case HatchStyle.Percent60: case HatchStyle.Percent70: case HatchStyle.Percent75: case HatchStyle.Percent80: case HatchStyle.Percent90: drawPattern = HatchPercentage; break; case HatchStyle.Sphere: drawPattern = HatchSphere; break; case HatchStyle.DashedDownwardDiagonal: patternTransform = CGAffineTransform.MakeScale(-1, 1); drawPattern = HatchDashedDiagonal; break; case HatchStyle.DashedUpwardDiagonal: drawPattern = HatchDashedDiagonal; break; case HatchStyle.DashedHorizontal: drawPattern = HatchDashedHorizontal; break; case HatchStyle.DashedVertical: patternTransform = CGAffineTransform.MakeRotation(-90 * (float)Math.PI / 180); drawPattern = HatchDashedHorizontal; break; case HatchStyle.LargeConfetti: case HatchStyle.SmallConfetti: drawPattern = HatchConfetti; break; case HatchStyle.ZigZag: drawPattern = HatchZigZag; break; case HatchStyle.Wave: drawPattern = HatchWave; break; case HatchStyle.HorizontalBrick: drawPattern = HatchHorizontalBrick; break; case HatchStyle.DiagonalBrick: drawPattern = HatchDiagonalBrick; break; // case HatchStyle.Weave: // drawPattern = HatchWeave; // break; case HatchStyle.Trellis: drawPattern = HatchTrellis; break; case HatchStyle.LargeCheckerBoard: case HatchStyle.SmallCheckerBoard: drawPattern = HatchCheckered; break; case HatchStyle.OutlinedDiamond: drawPattern = HatchOutlinedDiamond; break; case HatchStyle.SolidDiamond: drawPattern = HatchSolidDiamond; break; case HatchStyle.DottedDiamond: drawPattern = HatchDottedDiamond; break; case HatchStyle.Divot: drawPattern = HatchDivot; break; case HatchStyle.Shingle: drawPattern = HatchShingle; break; case HatchStyle.Plaid: drawPattern = HatchPlaid; break; default: drawPattern = DrawPolkaDotPattern; break; } //set the pattern as the Current Context’s fill pattern var pattern = new CGPattern(patternRect, patternTransform, hatch_width, hatch_height, CGPatternTiling.NoDistortion, true, drawPattern); //we dont need to set any color, as the pattern cell itself has chosen its own color graphics.context.SetFillPattern(pattern, new nfloat[] { 1 }); graphics.context.SetStrokePattern(pattern, new nfloat[] { 1 }); graphics.LastBrush = this; // I am setting this to be used for Text coloring in DrawString graphics.lastBrushColor = foreColor; }
public CGContextCanvas(CGContext context) { this.context = context; // context.InterpolationQuality = CGInterpolationQuality.High; context.TextMatrix = CGAffineTransform.MakeScale(1, -1); }
public void UpdateCell(Post post) { _currentPost = post; _scheduledWorkAvatar?.Cancel(); if (!string.IsNullOrEmpty(_currentPost.Avatar)) { _scheduledWorkAvatar = ImageService.Instance.LoadUrl(_currentPost.Avatar, TimeSpan.FromDays(30)) .LoadingPlaceholder("ic_noavatar.png") .ErrorPlaceholder("ic_noavatar.png") .FadeAnimation(false, false, 0) .DownSample(200) .Into(avatar); } else { avatar.Image = UIImage.FromBundle("ic_noavatar"); } if (_currentPost.VoteChanging) { Animate(); } else { likeButton.Transform = CGAffineTransform.MakeScale(1f, 1f); likeButton.Selected = _currentPost.Vote; likeButton.Enabled = true; } commentText.Text = _currentPost.Body; loginLabel.Text = _currentPost.Author; //costLabel.Text = BaseViewController.ToFormatedCurrencyString(_currentPost.TotalPayoutReward); timestamp.Text = _currentPost.Created.ToPostTime(); likeLabel.Text = AppSettings.LocalizationManager.GetText(_currentPost.NetLikes == 1 ? LocalizationKeys.Like : LocalizationKeys.Likes, _currentPost.NetLikes); flagLabel.Text = AppSettings.LocalizationManager.GetText(_currentPost.NetFlags == 1 ? LocalizationKeys.Flag : LocalizationKeys.Flags, _currentPost.NetFlags); if (!_isInitialized) { avatar.Layer.CornerRadius = avatar.Frame.Size.Width / 2; var tap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); var costTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Profile, _currentPost); }); var replyTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Reply, _currentPost); }); var likersTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Voters, _currentPost); }); var flagersTap = new UITapGestureRecognizer(() => { CellAction?.Invoke(ActionType.Flagers, _currentPost); }); replyButton.AddGestureRecognizer(replyTap); profileTapView.AddGestureRecognizer(tap); costLabel.AddGestureRecognizer(costTap); likeLabel.AddGestureRecognizer(likersTap); flagLabel.AddGestureRecognizer(flagersTap); commentText.Font = Helpers.Constants.Regular14; loginLabel.Font = Helpers.Constants.Semibold14; likeLabel.Font = Helpers.Constants.Regular12; costLabel.Font = Helpers.Constants.Regular12; replyButton.Font = Helpers.Constants.Regular12; timestamp.Font = Helpers.Constants.Regular12; likeButton.TouchDown += LikeTap; otherActionButton.TouchDown += MoreTap; _isInitialized = true; if (!BasePresenter.User.IsAuthenticated) { replyButton.Hidden = true; replyHiddenConstraint.Active = true; replyVisibleConstraint.Active = false; } } if (_currentPost.NetFlags > 0) { flagLabel.Hidden = false; flagVisibleConstraint.Active = true; flagHiddenConstraint.Active = false; } else { flagVisibleConstraint.Active = false; flagHiddenConstraint.Active = true; flagLabel.Hidden = true; } if (_currentPost.NetLikes > 0) { likeLabel.Hidden = false; flagVisibleConstraint.Active = true; likeHiddenConstraint.Active = false; } else { likeLabel.Hidden = true; flagVisibleConstraint.Active = false; likeHiddenConstraint.Active = true; } }
private CALayer CreateLayer() { var path = this.GetPath(); if (path == null) { return(null); } var pathBounds = path.PathBoundingBox; if ( nfloat.IsInfinity(pathBounds.Left) || nfloat.IsInfinity(pathBounds.Left) ) { if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { this.Log().Debug($"Ignoring path with invalid bounds {pathBounds}"); } return(null); } var transform = CGAffineTransform.MakeIdentity(); var scaleX = _scaleX; var scaleY = _scaleY; switch (this.Stretch) { case Stretch.Fill: case Stretch.None: break; case Stretch.Uniform: scaleX = (nfloat)Math.Min(_scaleX, _scaleY); scaleY = scaleX; break; case Stretch.UniformToFill: scaleX = (nfloat)Math.Max(_scaleX, _scaleY); scaleY = scaleX; break; } transform = CGAffineTransform.MakeScale(scaleX, scaleY); if (Stretch != Stretch.None) { // When stretching, we can't use 0,0 as the origin, but must instead // use the path's bounds. transform.Translate(-pathBounds.Left * scaleX, -pathBounds.Top * scaleY); } if (!ShouldPreserveOrigin) { //We need to translate the shape to take in account the stroke thickness transform.Translate((nfloat)ActualStrokeThickness * 0.5f, (nfloat)ActualStrokeThickness * 0.5f); } if (nfloat.IsNaN(transform.x0) || nfloat.IsNaN(transform.y0) || nfloat.IsNaN(transform.xx) || nfloat.IsNaN(transform.yy) || nfloat.IsNaN(transform.xy) || nfloat.IsNaN(transform.yx) ) { //transformedPath creation will crash natively if the transform contains NaNs throw new InvalidOperationException($"transform {transform} contains NaN values, transformation will fail."); } var colorFill = Fill as SolidColorBrush ?? SolidColorBrushHelper.Transparent; var imageFill = Fill as ImageBrush; var gradientFill = Fill as LinearGradientBrush; var stroke = this.Stroke as SolidColorBrush ?? SolidColorBrushHelper.Transparent; var transformedPath = new CGPath(path, transform); var layer = new CAShapeLayer() { Path = transformedPath, StrokeColor = stroke.ColorWithOpacity, LineWidth = (nfloat)ActualStrokeThickness, }; if (colorFill != null) { layer.FillColor = colorFill.ColorWithOpacity; } if (imageFill != null) { var fillMask = new CAShapeLayer() { Path = path, Frame = Bounds, // We only use the fill color to create the mask area FillColor = _Color.White.CGColor, }; CreateImageBrushLayers( layer, imageFill, fillMask ); } else if (gradientFill != null) { var fillMask = new CAShapeLayer() { Path = transformedPath, Frame = Bounds, // We only use the fill color to create the mask area FillColor = _Color.White.CGColor, }; var gradientLayer = gradientFill.GetLayer(Frame.Size); gradientLayer.Frame = Bounds; gradientLayer.Mask = fillMask; gradientLayer.MasksToBounds = true; layer.AddSublayer(gradientLayer); } if (StrokeDashArray != null) { var pattern = StrokeDashArray.Select(d => (global::Foundation.NSNumber)d).ToArray(); layer.LineDashPhase = 0; // Starting position of the pattern layer.LineDashPattern = pattern; } return(layer); }
protected virtual void SetupViews() { View.BackgroundColor = UIColor.Black; BackgroundView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false }; BackgroundView.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("light.png")); HeaderView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false, }; HeaderLabel = new UILabel { Font = UIFont.SystemFontOfSize(80), Text = "iOS 13", AdjustsFontSizeToFitWidth = true, TextAlignment = UITextAlignment.Center, TextColor = UIColor.White, TranslatesAutoresizingMaskIntoConstraints = false }; HeaderLabel.Layer.ShadowOffset = CGSize.Empty; HeaderLabel.Layer.ShadowColor = UIColor.Black.CGColor; HeaderLabel.Layer.ShadowOpacity = .75f; StartLabel = new UILabel { Text = "OUT NOW", TextColor = UIColor.White, TextAlignment = UITextAlignment.Center, Font = UIFont.SystemFontOfSize(24), TranslatesAutoresizingMaskIntoConstraints = false }; StartLabel.Layer.ShadowOffset = CGSize.Empty; StartLabel.Layer.ShadowColor = UIColor.Black.CGColor; StartLabel.Layer.ShadowOpacity = .75f; PresentationKindSegmentedControl = new UISegmentedControl("present", "new", "reuse") { TranslatesAutoresizingMaskIntoConstraints = false, TintColor = UIColor.White, Transform = CGAffineTransform.MakeScale(.85f, .85f), SelectedSegment = 0, }; MenuView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false }; MenuContainerImageView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false, Alpha = 0, }; MenuTableView = new UITableView { TranslatesAutoresizingMaskIntoConstraints = false, SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine, SeparatorColor = UIColor.White.ColorWithAlpha(.1f), BackgroundColor = UIColor.Clear, TableFooterView = new UIView { } }; HeaderView.AddSubviews(HeaderLabel, StartLabel, PresentationKindSegmentedControl); MenuView.AddSubviews(MenuContainerImageView); MenuView.InsertSubviewAbove(MenuTableView, MenuContainerImageView); View.AddSubviews(BackgroundView, HeaderView, MenuView); View.AddConstraints(new[] { NSLayoutConstraint.Create(BackgroundView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 100, -100), NSLayoutConstraint.Create(BackgroundView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 100, 100), NSLayoutConstraint.Create(BackgroundView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 100, 100), NSLayoutConstraint.Create(BackgroundView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 100, -100), NSLayoutConstraint.Create(HeaderLabel, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.CenterY, 1, 5), NSLayoutConstraint.Create(HeaderLabel, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.CenterX, 1, 0), NSLayoutConstraint.Create(HeaderLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.Leading, 1, -10), NSLayoutConstraint.Create(HeaderLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.Trailing, 1, 10), NSLayoutConstraint.Create(StartLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, HeaderLabel, NSLayoutAttribute.Bottom, 1, -10), NSLayoutConstraint.Create(StartLabel, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.CenterX, 1, 0), NSLayoutConstraint.Create(StartLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.Leading, 1, -10), NSLayoutConstraint.Create(StartLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, HeaderView, NSLayoutAttribute.Trailing, 1, 10), NSLayoutConstraint.Create(PresentationKindSegmentedControl, NSLayoutAttribute.Top, NSLayoutRelation.Equal, StartLabel, NSLayoutAttribute.Bottom, 1, 0), NSLayoutConstraint.Create(PresentationKindSegmentedControl, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, StartLabel, NSLayoutAttribute.CenterX, 1, 0), NSLayoutConstraint.Create(HeaderView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1, 0), NSLayoutConstraint.Create(HeaderView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1, 0), NSLayoutConstraint.Create(HeaderView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, 0), NSLayoutConstraint.Create(HeaderView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, 1, 180), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.Leading, NSLayoutRelation.GreaterThanOrEqual, View, NSLayoutAttribute.Leading, 1, 0), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.Trailing, NSLayoutRelation.GreaterThanOrEqual, View, NSLayoutAttribute.Trailing, 1, 0), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1, -15), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, PresentationKindSegmentedControl, NSLayoutAttribute.Bottom, 1, 0), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.Width, NSLayoutRelation.LessThanOrEqual, 1, 600), NSLayoutConstraint.Create(MenuView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1, 0), NSLayoutConstraint.Create(MenuContainerImageView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, MenuView, NSLayoutAttribute.Leading, 1, 0), NSLayoutConstraint.Create(MenuContainerImageView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, MenuView, NSLayoutAttribute.Trailing, 1, -0), NSLayoutConstraint.Create(MenuContainerImageView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, MenuView, NSLayoutAttribute.Bottom, 1, -0), NSLayoutConstraint.Create(MenuContainerImageView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, MenuView, NSLayoutAttribute.Top, 1, 0), NSLayoutConstraint.Create(MenuTableView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, MenuContainerImageView, NSLayoutAttribute.Leading, 1, MenuViewPadding), NSLayoutConstraint.Create(MenuTableView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, MenuContainerImageView, NSLayoutAttribute.Trailing, 1, -MenuViewPadding), NSLayoutConstraint.Create(MenuTableView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, MenuContainerImageView, NSLayoutAttribute.Bottom, 1, 20), NSLayoutConstraint.Create(MenuTableView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, MenuContainerImageView, NSLayoutAttribute.Top, 1, MenuViewPadding / 2 + 2), }); }