MonoTouch:圆形UIImage便捷方法

时间:2012-01-22 00:55:51

标签: c# ios xamarin.ios uiimage

是否有MonoTouch内置方法来舍入UIImage的边缘?

我似乎记得曾经看过它。

5 个答案:

答案 0 :(得分:3)

舍入UIImage会产生另一个UIImage。

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

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

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

你可以看到TweetStation如何将它用于它的Glass Buttons:

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

答案 1 :(得分:3)

这是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;
}

答案 2 :(得分:2)

在MonoTouch(以及iOS本身)中,您无法在UIImage本身上执行此操作。但是,您可以通过操作其UIImageView属性在Layer上执行此操作。

请参阅此answer以获取易于转换为C#的Objective-C示例。

答案 3 :(得分:1)

我还建议你在introduction-to-calayers-tutorial上学习以下教程。它涵盖了iOS中自定义图层的有趣内容。

希望它有所帮助。

答案 4 :(得分:0)

基于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;
}