tag:blogger.com,1999:blog-59465307047421309702024-03-06T16:20:07.273+08:00Jax 的工作紀錄除了在整理學習上的經驗,同時也能幫助其他需要的人Jax Huhttp://www.blogger.com/profile/01953021685585893658noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-5946530704742130970.post-40523079476201578702014-02-21T17:43:00.002+08:002023-02-25T21:33:00.264+08:00[T4] url, base64, sprite 三種格式的 icons.css 產生器之前有寫過 <a href="/2013/08/php-make-icons-css.html">[PHP] url, base64, sprite 三種格式的 icons.css 產生器</a>,這次換用 C# T4 Text Templates 來製作這個功能:<br />
<br />
<pre class="cs" name="code">int spriteGap = 30;
var scanTypes = new string[]{".jpg", ".gif", ".png"};
string workDirectory =
Path.GetDirectoryName(this.Host.TemplateFile);
/* 取得圖檔資訊 */
List<ImageInfo> imageList = Directory
.EnumerateFiles(Path.Combine(workDirectory, "icons"))
.Where(path => scanTypes.Contains(Path.GetExtension(path)))
.Select(path =>
{
var image = Image.FromFile(path);
return new ImageInfo{
FilePath = path,
FileName = Path.GetFileName(path),
IconImage = image,
IconName = Path.GetFileNameWithoutExtension(path),
TopOffset = 0,
Width = image.Width,
Height = image.Height,
IsAnimated = ImageAnimator.CanAnimate(image),
};
})
.OrderBy(info => info.IsAnimated)
.ToList();
/*檢查重複的圖檔名稱*/
List<string> repeatList = imageList.GroupBy(info => info.IconName)
.Where(g => g.Count() > 1)
.SelectMany(g => g.Select(x => x.FileName))
.ToList();
if(repeatList.Count > 0){
throw new Exception(
"出現重複的圖檔名稱[" + String.Join(", ", repeatList) + "]"
);
}
/* 製作 CSS Sprite */
int sumHeight = imageList.Sum( info => info.Height);
int spriteWidth = imageList.Max( info => info.Width);
int spriteHeight = sumHeight + (imageList.Count - 1) * spriteGap;
var bitmap = new Bitmap(spriteWidth, spriteHeight);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
int nextTop = 0;
for(int i=0; i< imageList.Count; i++){
/*忽略具有動畫的 GIF 圖片*/
if(imageList[i].IsAnimated){ continue; }
imageList[i].TopOffset = nextTop;
graphics.DrawImage(imageList[i].IconImage, 0, nextTop);
nextTop = nextTop + imageList[i].Height + spriteGap;
}
graphics.Save();
}
SaveOutput("icons.sprite.png");
bitmap.Save(
Path.Combine(workDirectory, "icons.sprite.png"),
ImageFormat.Png
);
bitmap.Dispose();
</pre><br />
下載完整程式: <a href="https://dl.dropboxusercontent.com/u/16784943/code-demo/t4_make_icons_css.zip">t4_make_icons_css.zip</a><br />
Jax Huhttp://www.blogger.com/profile/01953021685585893658noreply@blogger.com0