2012-01-22 25 views

回答

3

舍入UIImage會產生另一個UIImage。

如果您創建一個CGContext以與原始圖像大小相同的方式進行渲染,然後添加一個帶圓角的剪裁路徑並呈現原始UIImage,則可以執行此操作。

然後,您可以將UIImage拉出CGContext。

另一種選擇是避免中間步驟,就是在你的上下文繪圖中推送圖形狀態,添加圓形路徑作爲剪切路徑,繪製圖像然後彈出圖形狀態返回到此處。

你可以看到TweetStation如何使用這爲它的玻璃按鈕:

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

2

在MonoTouch(和iOS本身)中,它不是您可以在UIImage本身上執行的操作。但是,您可以通過操縱其Layer屬性在UIImageView上執行此操作。

看到這個answer爲一個Objective-C的例子,很容易轉換爲C#。

3

這裏是MonoTouch的用戶尋找一個快速的輔助函數一個漂亮的代碼幫手。 Tweeked代碼來自於優秀的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; 
} 
+0

好的!但在圖片大小調整時失敗......任何想法? – cvsguimaraes

+0

我改進了你的方法... – cvsguimaraes

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