MonoTouch:圆形UIImage便捷方法

是否有MonoTouch内置方法来绕过UIImage的边缘?

我好像记得曾经见过它。

舍入UIImage将产生另一个UIImage。

如果创建CGContext以与原始图像大小相同,则可以执行此操作,然后添加带有圆角的剪切路径并渲染原始UIImage。

然后你可以将UIImage从CGContext中拉出来。

另一个选择是避免中间步骤,即在上下文绘图中推送图形状态,将圆角路径添加为剪切路径,绘制图像然后弹出图形状态以返回到此状态。

您可以看到TweetStation如何将其用于其Glass按钮:

https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Utilities/GlassButton.cs#L76

这是MonoTouch用户寻找快速帮助函数的一个很好的代码帮助器。 Tweeked代码来自Excellent Xamarin.com网站:

 public static UIImage RounderCorners (UIImage image, float width, float radius) { UIGraphics.BeginImageContext (new SizeF (width, width)); var c = UIGraphics.GetCurrentContext (); //Note: You need to write the Device.IsRetina code yourself radius = Device.IsRetina ? radius * 2 : radius; c.BeginPath (); c.MoveTo (width, width / 2); c.AddArcToPoint (width, width, width / 2, width, radius); c.AddArcToPoint (0, width, 0, width / 2, radius); c.AddArcToPoint (0, 0, width / 2, 0, radius); c.AddArcToPoint (width, 0, width, width / 2, radius); c.ClosePath (); c.Clip (); image.Draw (new PointF (0, 0)); var converted = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); return converted; } 

在MonoTouch(和iOS本身)中,你不能在UIImage做些什么。 但是,您可以通过操作其Layer属性在UIImageView上执行此操作。

请参阅此答案,了解一个易于转换为C#的Objective-C示例。

我还建议您阅读以下有关介绍-calayers-教程的教程 。 它涵盖了在iOS中自定义图层的有趣内容。

希望能帮助到你。

根据BahaiResearch.com的回答,我为非方形图像和圆度百分比而不是字面半径制作了另一种方法。

我不确定它是否会正确生成省略号。 所以如果有人可以测试甚至改进这种方法,我将不胜感激。

 private static UIImage RoundCorners (UIImage image, float roundnessPercentage) { float width = image.Size.Width; float height = image.Size.Height; float radius = ((width+height)/2) * (roundnessPercentage/(100*2)); UIGraphics.BeginImageContext (new SizeF (width, height)); CGContext c = UIGraphics.GetCurrentContext(); c.BeginPath (); c.MoveTo(width, height/2); //Bottom-right Corner c.AddArcToPoint(width, height, height / 2, width, radius); //Bottom-left Corner c.AddArcToPoint(0, height, 0, 0, radius); //Top-left Corner c.AddArcToPoint(0, 0, width/2, 0, radius); //Top-right Corner c.AddArcToPoint(width, 0, width, height/2, radius); c.ClosePath(); c.Clip(); image.Draw (new PointF (0, 0)); UIImage converted = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext (); return converted; } 
Interesting Posts