2

我有一个带有大量小图标的精灵,并且经常维护 Illustrator 文件,以至于我想要一个脚本来尽可能地自动排列组对象而不会重叠,并且理想情况下具有某种最小可能排列的感觉。

我已经为 Adob​​e 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}

CS4 输出 JSON 的 PHP 解析器

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,但如果没有一些自动包装,就不能自豪地做到这一点。)

4

1 回答 1

1

到目前为止非常整洁的脚本。您可能应该研究Rectangle 打包并选择一种算法。通过简单的搜索,我发现这个项目看起来很有希望。

有点务实的一面,可能也值得看看TexturePacker。它不是免费的,但价格合理。

于 2013-02-12T10:36:23.610 回答