I have the following code:
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var gradient = new CAGradientLayer();
gradient.Frame = view.Bounds;
gradient.Colors = colors;
var mask = new CALayer();
mask.Frame = view.Bounds;
mask.Contents = view.Image.CGImage;
mask.ContentsGravity = CALayer.GravityCenter;
gradient.Mask = mask;
view.Layer.AddSublayer(gradient);
}
which produces the following result:
"view" is a UIImageView which is centered perfectly.
The number "1" is exactly in the middle. Here you can see that the mask is not centered perfectly.
The image here is the heart icon from the standard resources, it's not a custom image. (If e.g. used in a button, then it's centered perfectly).
Before posting I've tried all possible combinations when it comes to setting Frame and Bounds, the mask is always off-center by a few pixels.
Someone else reported a similar issue here, but there was no solution: Gradient Color over Template Image in Swift 4
This makes me believe that there's a bug with how masks are applied. Could anyone confirm?