To customize my app's appearance, I've implemented a custom renderer for buttons, setting a gradient background image on them. So far, that's working fine.
However, when I set a corner radius, the edges appear very blurry. I thought it might be due to the difference between screen coordinates and actual resolution, but when I apply a factor (2 or 3) to accommodate for that it just completely screws up the shape (while still being blurred).
Here's a screenshot, taken on an iPhone X (note the resolution of entry and images):
Here's the code generating the background:
private UIImage CreateGradientBackground(Color startColor, Color endColor)
{
var gradientLayer = new CAGradientLayer();
if (Control == null)
return null;
gradientLayer.Bounds = Control.Bounds;
gradientLayer.CornerRadius = (Control.Bounds.Width < Control.Bounds.Height) ?
Control.Bounds.Width / 2 :
Control.Bounds.Height / 2;
gradientLayer.Colors = new CGColor[] { startColor.ToCGColor(), endColor.ToCGColor() };
gradientLayer.StartPoint = new CGPoint(0, 0.5);
gradientLayer.EndPoint = new CGPoint(1, 0.5);
UIGraphics.BeginImageContext(gradientLayer.Bounds.Size);
if (UIGraphics.GetCurrentContext() == null)
return null;
gradientLayer.RenderInContext(UIGraphics.GetCurrentContext());
UIImage image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
This is how it's applied (for all the various states):
Control.SetBackgroundImage(gradientBackground, UIControlState.Normal);
Does anyone have an idea how to fix this?
Thanks a lot!
SOLUTION (thanks to NickSpag!)
1: set the appropriate contents scale on the gradient layer:
gradientLayer.ContentsScale = UIScreen.MainScreen.Scale;
2: get the correct image context:
UIGraphics.BeginImageContextWithOptions(gradientLayer.Bounds.Size, false, UIScreen.MainScreen.Scale);