Pesquisa

segunda-feira, 3 de janeiro de 2011

Imagem com cantos arredondados

Para fazer imagens com cantos arredondados sem que aconteça problemas em diferentes navegadores, basta renderizar as imagens no servidor.

Segue abaixo um exemplo de como fazer:

Pagina RoundCorner.aspx:

Página responsável por ajustar os cantos das imagens.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>

<script runat="server">

void Page_Init(Object sender,EventArgs e) {

string imagem = Request.QueryString["Imagem"].ToString();
string path = Server.MapPath(String.Format("~/{0}", imagem));
int roundedDia = 20;

using(System.Drawing.Image imgin = System.Drawing.Image.FromFile(path)){

System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imgin.Width, imgin.Height);
Graphics g = Graphics.FromImage(bitmap);

//Define a cor do canto arredondado
Color cor = Color.FromArgb(29, 29, 29);
g.Clear(cor);

Brush brush = new System.Drawing.TextureBrush(imgin);

FillRoundedRectangle(g, new Rectangle(0, 0, imgin.Width, imgin.Height), roundedDia, brush);

// done with drawing dispose graphics object.

g.Dispose();

// Stream Image to client.

Response.Clear();

Response.ContentType = "image/pjpeg";

bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

Response.End();

// dispose bitmap object.

bitmap.Dispose();
}
}

public static void FillRoundedRectangle(Graphics g,Rectangle r,int d,Brush b){

// anti alias distorts fill so remove it.
System.Drawing.Drawing2D.SmoothingMode mode = g.SmoothingMode ;

g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
g.FillPie(b,r.X,r.Y,d,d,180,90);
g.FillPie(b,r.X+r.Width-d,r.Y,d,d,270,90);
g.FillPie(b,r.X ,r.Y+r.Height -d,d,d,90,90);
g.FillPie(b,r.X +r.Width-d,r.Y+r.Height -d,d,d,0,90);
g.FillRectangle(b,r.X + d/2,r.Y,r.Width-d,d/2);
g.FillRectangle(b,r.X ,r.Y +d/2,r.Width,r.Height-d);
g.FillRectangle(b,r.X + d/2,r.Y + r.Height-d/2,r.Width-d,d/2);
g.SmoothingMode = mode;
}

</script>

Página que utiliza a RoundCorner.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image runat="server" ID="img" ImageUrl="~/RoundCorner.aspx?Imagem=imagem.jpg" />
</div>
</form>
</body>
</html>

Créditos: Tiago Bandeira


Um comentário: