2013-02-12 57 views
2

我有一个精灵,有很多小图标,并且经常保持Illustrator文件足够多,我希望脚本能够尽可能接近地自动排列组对象,而且不会重叠,并且最好带有某种意义上的尽可能小的安排。最小空间雪碧安排

我已经为Adobe Illustrator CS4编写了一个脚本,在每个选定对象的尺寸和坐标上创建一个JSON文件。从那里,我写了这些PHP函数来编写和测试每个图标的CSS。 (它也可以从4项角的图标和2重复的x/y的边界创建边界,但是这需要一个层的命名约定我赞成CSS3的抛弃。

插图CS4脚本

var i,j=0;var destFolder=Folder.selectDialog('Select the folder where you want to save the exported files.','/c/DATA/TrackAuthority/HEAD/wwwroot/js/');var activeDocument=app.activeDocument;var ssLayers=selection;var components=getActiveLayers(activeDocument,"COMPONENTS");var singlesStr=''var compStr=''var fileName=activeDocument.name.substr(0,activeDocument.name.indexOf('.'))+'_json';var fileType='txt';if(ssLayers.length==0){alert("select the layers you want to export")}else{if(destFolder!=null){buildComponentsArray();if(osize(components)>0||singlesStr.length>0){var master='{"components": [{}],';master+='"singles": ['+singlesStr+']}';writeXML(master)}else{alert("no xml constructed")}}else{alert("pick a folder!")}}function objToXML(key){if(typeof(key)=="object"){for(var value in key){alert(key+" is: "+value+' : '+key[value])}}else{alert('string: '+key)}}function buildComponentsArray(){for(i=0;i<ssLayers.length;i++){var className=ssLayers[i].name;var componentName=ssLayers[i].layer.name;var visibleBounds=ssLayers[i].visibleBounds;var x1=ssLayers[i].left;var y1=ssLayers[i].top;x1=(className.indexOf('-x')>-1)?'0':Math.abs(Math.ceil(x1))*-1;y1=(className.indexOf('-y')>-1)?'0':Math.abs(Math.ceil(y1))*-1;var spriteWidth=(className.indexOf('-x')>-1)?'"100%"':'"'+Math.ceil(ssLayers[i].width)+'px"';var spriteHeight=(className.indexOf('-y')>-1)?'"100%"':'"'+Math.ceil(ssLayers[i].height)+'px"';if(className!=''&&className!=null&&className!=undefined){var itemStr='{"classname": "'+className+'", "x":'+x1+', "y":'+y1+', "width":'+spriteWidth+', "height":'+spriteHeight+'}';if(componentName=='SINGLES'){if(singlesStr!='')singlesStr+=',';singlesStr+=itemStr}else if(components[componentName]&&components[componentName][className]){components[componentName][className]=itemStr}}}if(osize(components)>0){compStr=flattenObj(components)}}function flattenObj(obj){var all='';for(var comp in obj){if(all!='')all+=',';all+='{"'+comp+'":[';var items='';for(var sprite in obj[comp]){if(items!='')items+=',';items+=obj[comp][sprite]}all+=items;all+=']}'}return all}function tracer(key){if(typeof(key)=="object"){for(var value in key){alert(value+' : '+key[value])}}else{alert('string: '+key)}}function writeXML(fileContents){if(destFolder!=null){alert('Files are saved as SWF in '+destFolder);var xmlFile=new File(destFolder.toString()+'/'+fileName+'.'+fileType);if(xmlFile.exists){allow=confirm("The file "+xmlFile+" already exists.\nDo you wish to replace it and ALL other duplicate files?",true,"Duplicate File Found");if(allow)xmlFile.remove();else{var index=1;var newname=new File(destFolder.toString()+'/'+fileName+'-'+index+'.'+fileType);while(newname.exists){index++;newname=new File(destFolder.toString()+'/'+fileName+'-'+index+'.'+fileType)}xmlFile.rename(newname)}}xmlFile.open('w');xmlFile.write(fileContents);xmlFile.close();xmlFile.execute()}else{alert('No destination folder selected')}}function osize(obj){var size=0;for(var k in obj){size++}return size}function getActiveLayers(sourceDoc,layerName){var activeLayers=new Array();for(var j=0;j<sourceDoc.layers.length;j++){if(sourceDoc.layers[j].name==layerName){for(var i=0;i<sourceDoc.layers[j].layers.length;i++){var key=sourceDoc.layers[j].layers[i].name;activeLayers[key]=new Array()}}}return activeLayers} 

PHP JSON的解析器通过CS4

if(!defined('BASEPATH'))exit('No direct script access allowed');class manage extends MX_Controller{function __construct(){parent::__construct();}function someLatin($num=1,$sentence=true){$latin="Of all the currencies that you’re paid in, the only currency that you cannot replace is time. Money is a cheap thing. In the end, an idea is a reasonably cheap thing. But the investment of time is the scarcest of all resources; Stephen Hawking was absolutely right—the arrow of time points in one direction. And once you’ve spent that second, you cannot capture it again. So do not waste it. You should live life so that the moments in it are intense. Don’t live a ho-drum life, where you can’t remember [inaudible]. Do things that are intense. You need people around you who care enough about you to tell you you’re wrong in a way that you can hear it. This is a gift that you guys can give one another. There are a tremendous number of guys who I went to school with who enjoy calling me up and telling me I was an idiot. I find it extremely easy to hang up the phone and not pay attention. There are a small number of guys in pictures on the wall in my office who call me up and tell me I’m an idiot in such a way at the end of the conversation I say why? How? How can I avoid that? Thanks for calling. They tell me I’m an idiot about things I do in business; they tell me I’m an idiot about things I do with my personal life; they tell me I’m an idiot about things I do with my kids; they care enough to make the call, and they’re patient enough to let me hear them out. You’re going to end up being a director of a firm. You’re going to end up spending hours thinking through the strategy of a firm. Each one of you is worth having your own board of directors. Choose that group of people who are going to sit around you who are confident enough to provide you with advice, and who are talented enough to provide you with things you haven’t thought about, and who care about you enough to tell you the things that you’re doing wrong. Because I promise you—you will not see it. You will be blind in pursuit, passionate in pursuit, and dead wrong. If you’re gonna get a board of directors for a stupid firm, for God’s sake get a board of directors for you. And many of you will find at least one of those directors here while you’re at the Harvard Business School. Think about who that can be; think about who can give you that advice; and be prepared to give that advice to someone else. There’s nothing cooler than being in love, being together—by the way, seeing your kids make their way through life is a close second—the stupidest, dumbest thing you guys ever tell me is that we’re in love, and he’s gonna live in New York and I’m gonna live in San Francisco and we’re gonna meet in Chicago. This is beyond stupid. It turns out that the real way to build a relationship with one another is to sleep with one another. I mean every night. If you live with one another and really weave your life together, you will stay together. Everything else that I have done pales in comparison to the relationship that I have been able to develop with my wife Karen. I hope that each one of you will find a partner that you can share this journey with. It’s difficult to do, and by the way I’ve had some failures along the way. I was unsuccessful in my first marriage. I screwed it up. I screwed it up in a very predictable way: I put too much work into the world around me, and not enough work into the world I shared with my partner. It’s easy to do. There’s tremendous satisfaction in meeting the world’s needs that can leave you remarkably empty when it comes to building something with one another. When I see you on your fifth anniversaries, on your tenth anniversaries, on your fifteenth anniversaries, I know what I will be told. Everyone will have enough money. Everyone. Everyone who is unhappy will be unhappy for one of two reasons: they’re doing a job they hate and they’re afraid to change it; or they’re not in love. They’re doing all of this to share it with another, and they’re all alone. That’s been proven year five, year ten, year fifteen. That’s another gift you can give one another, because you can see that in one another and ask one another not only what are you doing, but how are you doing? Finally, kids are a remarkable thing. My daughter graduates from Columbia in about an hour and a half. I’m going to miss that graduation but I’ll see her Friday night. They are delightful things. They are gifts that I cannot possibly explain to you. But they are such a royal pain in the ass that I just want to make sure that I’ve told you that. You can’t microwave babies. They take time, they take walks, they take time talking about bugs, and you’ll have lives like the life I’ve lived, where you’ll find yourself living one week here and one week in Northern California, and one week every month in Eindhoven or Kyoto, and the time that you’re there to spend with those children will be highly taxed. You pay a price for that, and they do too. Time is your dearest investment; you’re going to manage how you invest it, and babies prosper with time, it’s a thing that you cannot outsource, and by the way, you’re going to have to put time in all those other things. But it is hugely satisfying for me to think about that little bitty kid getting a degree, a master’s in architecture, walking down the aisle this afternoon, and I hope you too get that. Finally, I should have spent more time fly-fishing. It’s a very cool sport. I pick something other than work—I intensely love work, I like teaching, I like all that stuff, it’s what I tend to do, but it probably would have been good if I had picked something that wasn’t quite so intense all of the time. I keep saying that I’m going to do it and I promise to spend more time on it next year. So I’ll come back to that definition—entrepreneurship is the relentless pursuit of opportunity beyond the constraints of the tangible resources under the firm’s control—and keep that pursuit of opportunity in your mind. I do not believe each one of you should be an entrepreneur, much less an entrepreneur tomorrow morning. I do believe that you should leave here with the choice, and make the choice that fits for you. There has never been a time in recorded history when the supply of capital did not overwhelm the supply of opportunity. As I’ve been here at the school, I’ve seen wave after wave of things rush through here, where this is going to be it, and you see MBAs lined up like surfers at La Jolla, hoping to time the wave. There’s always smart money, and then dumb money flows in and then there’s just tons of money and divergence from the mean, the mean goes negative, but the cream—the best investors, the best entrepreneurs, the best ideas—always rises to the top. Remember, in the venture side of this business, 90% of the returns have been locked in by less than 10% of the investors. If you look at the ventures, 67% of the return is in less than 5 % of the ventures. By the way, if you look at the distribution for-profit, not-for-profit, anywhere in the world, I think the same is likely to be true. So understand where you can get those disproportionate returns and understand who the cream is so you can hang out with them, and do things with them, and take on problems with them. There’s always technology change, there’s always change associated with globalization, and I believe right now we’re going to go through a tremendous amount of change associated with re-regulation because the world has relied too much on markets, both in financial markets and it’s depended too much on markets in environmental issues. I think that will create a whole raft of new and exciting businesses. And there’s always demographic change, and demographic change is really cool because it’s totally predictable. But as I sit here in front of you today, there has never been more opportunity to do things, to build things today. There are more ways to change the world today than there ever have been. And I think you all are in a unique position to be able to do that. When you do that, this is my favorite quote from Walt Disney, he understood two problems—how to make pictures just to make money and make money to make more pictures. Money is a shallow thing. The things you can do with it are a huge amount of fun—whether it’s solving problems or creating your visions or bringing groups of people together to do ambitious things…but it’s not the end in itself. It’s a means to something, and you can do that every time you fall into a new problem. You make money because businesses need money the same way automobiles need [inaudible]. So where are we going now? I honestly don’t know. I don’t know where all of this will lead for you guys. I wish I did and I wish I could save you from some of the things that will be painful in that journey. I will think about you the way I think about Randy and Joe, and something will blip across the screen and I’ll think my God, what happened to them, and some email will be there, but I can’t do that. I do think you can have a lot of fun finding out what the future is. And the one thing I can give you is a limited lifetime warrantee. If you’ve got something you want to talk about, get in touch with me. And when I’m not here there will be someone else from HBS that’s here to take that call. Remember to call one another. You have a relationship with one another that can be uniquely valuable in helping you understand the world around you. So…you’ve got a warranty. Use it. Thanks very much—I enjoyed studying with you guys, I learned a lot. One last thing. I will call you and I will ask you to help the next group of students that are here, and I will expect you to do that. Just like I expect the ones that have come before you to do that. There’s something I would urge you to think about, and I would urge you to think about carefully at some point in time about working with young people. The thing that’s exciting about working with young people is that through their eyes you see the future. You see years beyond where I see. You know things that I do not see. But that is not the great gift. Through you I see myself as I once was, and in that I am reborn. I get to go back and live life again in an exciting way. All of you should think about that because it’s a gift that that person I send to you can give you, and that you should repay. Thanks again [Thunderous applause, some weeping].";$parts=explode(".",trim($latin,"."));$final="";$part="";if($sentence==true){if($num>count($parts))$num=count($parts)-1;for($i=0;$i<=$num;$i++){$part=$parts[mt_rand(0,count($parts)-1)];$final.=ucfirst($part);$final.=". ";}$final=trim($final,",");}else{$latin2=$parts[mt_rand(0,count($parts)-1)];if(empty($latin2))$latin2=$latin;$words=explode(" ",trim($latin2));if($num>count($words))$num=count($words)-1;for($i=0;$i<$num;$i++){$part=$words[$i];if($i==0)$final.=$part;else$final.=" ".$part;}$final=ucwords($final);}$final=trim($final);if(empty($final))$final="And Empty";return$final;}} 

PHP视图文件输出到建立的产生图标的演示页:

.tmmss { background:transparent url(<?=$spritePath;?>) 0 -100px no-repeat; padding:0; float:left; overflow:hidden; height:50px; width:50px; z-index:100; } <?php foreach($singles as$single){$classname=$single['classname'];$item=' .tmmss.'.$classname.' { background-position: '.$single['x'].'px '.$single['y'].'px; width:'.$single['width'].'; height:'.$single['height'].';';if(strpos($classname,'-y')>-1)$item.='background-repeat:repeat-y;';if(strpos($classname,'-x')>-1)$item.='background-repeat:repeat-x;';$item.='} ';echo"\n";echo$item;}; 

(所有我一直想叫它'SuperSprite',duah-da-nut-dauh,但不能自豪地这样做,没有一些自动包装)

回答

1

到目前为止很漂亮的脚本。你应该看看Rectangle packing并选择一种算法。通过简单的搜索,我发现this project看起来很有希望。

在实用的一面,也许值得也看看TexturePacker。 这不是免费的,但价格合理。

+0

感谢乔治!乍看之下,TexturePackage看起来非常完整和合理的购买。 同时,从他们的网站(http://codeincomplete.com/posts/2011/5/7/bin_packing/example/)看演示,似乎 – 2013-02-12 16:56:38

+0

不用担心,随意投票/标记,因为你认为合适。很酷,你也可以从命令行调用TexturePacker。不幸的是,我还没有在Illustrator JS文档中找到任何有关如何调用其他应用程序的信息,希望可以编写一个简单的工作流程:遍历ai文档,将每个元素导出为文件夹中的优化png,将该文件夹传递给TexturePacker。 – 2013-02-12 17:18:03

+0

好主意。我确实有一个旧的导出脚本,我会尝试恢复并在这里发布。 同时,我之前的评论被缩短了。 ...似乎这个简单的JS文件形成他们的演示可以直接合并到我的Illustrator脚本中,以收紧sprite - http://codeincomplete.com/posts/2011/5/7/bin_packing/packer.js - 然而它没有'最小可能'的包装能力。 – 2013-02-12 17:32:46