您的位置:首页 > 其它

[Web Chart系列之五] 3. 实战draw2d 之图形填充色(纯色 or 渐变)

2013-03-18 18:06 399 查看


颜色渐变

draw2d 目前没有提供直接对Figure 设置渐变效果的API.

但是raphael 有提供, 这样的话基本上在draw2d实现渐变成为可能。


颜色渐变功能来源

raphael 提供的图形背景色渐变的设置:看例子

<!--Add by oscar999-->
</HTML>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Linear Gradient</title>
<script src="http://raphaeljs.com/raphael.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var paper = Raphael(10, 10, 800, 600);
var circle = paper.circle(150, 150, 150);
circle.attr({
"fill": "90-#f00:5-#00f:95",
"fill-opacity": 0.5
});
</script>
</body>
</html>
先看一下 raphael 官方API对于fill 设置渐变色的说明:

Linear gradient format: “
‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›
”, example: “
90-#fff-#000
” – 90°gradient from white to black or “
0-#fff-#f00:20-#000
” – 0° gradient from white via red (at 20%) to black.

radial gradient: “
r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›
”, example: “
r#fff-#000
” –gradient from white to black or “
r(0.25, 0.75)#fff-#000
” – gradient from white to black with focus pointat 0.25, 0.75.
Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.

这里简单说明一下 --
"fill": "90-#f00:5-#00f:95"
90 设置的是渐变的方向的角度, 90 就是垂直。

从#f00渐变到#00f, :5 和:95 是偏移量。

如果对以上的理解还不是很清晰的话,就要追溯到源头了。

看看在SVG中是如何处理渐变的。

在 SVG 中,有两种主要的渐变类型:

线性渐变

放射性渐变

这里以 线性渐变来说明了:

<linearGradient> 可用来定义 SVG 的线性渐变。

<linearGradient> 标签必须嵌套在 <defs> 的内部。<defs> 标签是 definitions 的缩写,它可对诸如渐变之类的特殊元素进行定义。

线性渐变可被定义为水平、垂直或角形的渐变:

当 y1 和 y2 相等,而 x1 和 x2 不同时,可创建水平渐变

当 x1 和 x2 相等,而 y1 和 y2 不同时,可创建垂直渐变

当 x1 和 x2 不同,且 y1 和 y2 不同时,可创建角形渐变

看例子:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<defs>
<linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);
stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);
stop-opacity:1"/>
</linearGradient>
</defs>

<ellipse cx="200" cy="190" rx="85" ry="55"
style="fill:url(#orange_red)"/>

</svg>


代码解释:

<linearGradient> 标签的 id 属性可为渐变定义一个唯一的名称

fill:url(#orange_red) 属性把 ellipse 元素链接到此渐变

<linearGradient> 标签的 x1、x2、y1、y2 属性可定义渐变的开始和结束位置

渐变的颜色范围可由两种或多种颜色组成。每种颜色通过一个 <stop> 标签来规定。offset 属性用来定义渐变的开始和结束位置。

这下应该豁然了....


draw2d的处理方式

在Figure 对应的Class(比如draw2d.shape.basic.Rectangle)的repaint 方法中添加:

attributes.fill = "90-#fff:5-#000:95";
渐变颜色根据需要配置,也可以动态配置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: