首页 > 解决方案 > ClipToBounds 没有边框颜色问题 - Xamarin.iOS,C#

问题描述

程序:

代码:

UIImageView imageView = new UIImageView(); 
imageView.Layer.BorderWidth = 5f; //set border thickness
imageView.Layer.CornerRadius = 25; //make corner's rounded
imageView.Layer.BorderColor = UIColor.Red.CGColor; //set border color red
imageView.Image = new UIImage(imgPath); //set img
imageView.ClipsToBounds = true; //required - so image is rounded

问题:

如果我将边框颜色更改为白色(透明),您可以在每个角落看到小黑线。我怎样才能摆脱这些?

在此处输入图像描述

在此处输入图像描述

标签: c#xamarinxamarin.formsxamarin.iosuiimageview

解决方案


我查看了通过 Revel 在边界半径上渲染的核心动画层,那些是合成上的渲染伪影(我假设这些是原始图像颜色的半径计算中的迷你地图/抗锯齿中的舍入误差,但这只是一个疯狂的猜测......)

在此处输入图像描述

因此,如果您创建一个CAShapeLayer与您正在使用的半径相同的并将其应用为图层的蒙版,则工件会变得更小。(Core Animation 贝塞尔路径更准确但不完美?)

在此处输入图像描述

如果您创建一个在拐角半径上大一个像素的 CAShapeLayer 作为“hack”,则工件将被完全掩盖:

在此处输入图像描述

CAShapeLayer/蒙版修复示例:

UIImageView imageView = new UIImageView
{
    Image = UIImage.FromBundle("foo.jpg"),
    ClipsToBounds = true,
    Bounds = View.Bounds
};
imageView.Layer.BorderWidth = 5f; //set border thickness
imageView.Layer.CornerRadius = 25; //make corner's rounded
imageView.Layer.BorderColor = UIColor.White.CGColor; //set border color red
var maskingShapeLayer = new CAShapeLayer()
{
    Path = UIBezierPath.FromRoundedRect(imageView.Bounds, UIRectCorner.AllCorners, new CGSize(26, 26)).CGPath
};
imageView.Layer.Mask = maskingShapeLayer;

注意:也许“核心”核心动画专家可以首先解释渲染伪影存在于这些边界曲线上的方式,因为我仍然使用 CAShapeLayers 进行角掩蔽,即使在iOS 11+ 你可以像问题一样设置你的 UIView 的 Layer.CornerRadius 。


推荐阅读