級別: ★★☆☆☆
標籤:「iPhone app 圖標」「圖標生成」「啓動圖生成」「QiAppIconGenerator」
做者: Xs·H
審校: QiShare團隊php
一個完整的app都須要多種尺寸的圖標和啓動圖。通常狀況,設計師根據開發者提供的一套規則,設計出圖標和啓動圖供開發人員使用。但最近我利用業餘時間作了個app,不但願耽誤設計師較多時間,就只要了最大尺寸的圖標和啓動圖各一個。本想着找一下現成的工具,批量生成須要的的圖片,但最後沒有找到,只好使用Photoshop切出了不一樣尺寸的圖片。這期間,設計師還換過一次圖標和啓動圖,我就重複了切圖工做,這花費了我大量的時間。因而過後,做者開發了一個mac app——圖標&啓動圖生成器(簡稱生成器)以提升工做效率。做者用兩篇文章分別介紹生成器的使用和實現細節。git
接上篇文章,本篇文章介紹生成器的實現細節。github
生成器的工程很是簡單,能夠歸納爲一個界面、一個資源文件和一個ViewController。結構以下圖。算法
生成器app只有一個界面,由於界面複雜度較小,做者選用了Storyboard+Constraints的方式進行開發。下圖顯示了界面中的控件和約束狀況。數組
其中各控件對應的類以下所示。bash
控件 | 類 |
---|---|
圖片框 | NSImageView |
平臺選擇器 | NSComboBox |
路徑按鈕 | NSButton |
路徑文本框 | NSTextField |
導出按鈕 | NSButton |
app所支持的平臺規則數據從資源文件QiConfiguration.plist
中獲取。QiConfiguration.plist
至關於一個字典,每一個平臺對應着字典的一對key
和value
; value
是一個數組,存儲着該平臺所須要的一組尺寸規格數據(item); item
是尺寸規格數據的最小單元,內部標記了該尺寸規格的圖片的用途、名稱和尺寸。微信
QiConfiguration.plist
的具體結構以下圖所示。app
工程使用默認的ViewController
管理界面、資源數據和邏輯。 首先,界面控件元素在ViewController
中對應下圖中的5個實例。工具
其中,imageView
、platformBox
和pathField
不須要響應方法。而且,platfromBox
和_pathField
的默認/記憶數據由NSUserDefaults
管理。oop
static NSString * const selectedPlatformKey = @"selectedPlatform";
static NSString * const exportedPathKey = @"exportedPath";
複製代碼
- (void)viewDidLoad {
[super viewDidLoad];
NSString *selectedPlatform = [[NSUserDefaults standardUserDefaults] objectForKey:selectedPlatformKey];
[_platformBox selectItemWithObjectValue:selectedPlatform];
NSString *lastExportedPath = [[NSUserDefaults standardUserDefaults] objectForKey:exportedPathKey];
_pathField.stringValue = lastExportedPath ?: NSHomeDirectory();
}
複製代碼
這裏忽略這三個控件,重點介紹pathButton
和exportButton
的響應方法中的代碼邏輯。
pathButton
的響應方法負責打開文件目錄,並回傳選擇的路徑給pathField
,以顯示出來。 代碼以下:
- (IBAction)pathButtonClicked:(NSButton *)sender {
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
openPanel.canChooseDirectories = YES;
openPanel.canChooseFiles = NO;
openPanel.title = @"選擇導出目錄";
[openPanel beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse result) {
if (result == NSModalResponseOK) {
self.pathField.stringValue = openPanel.URL.path;
}
}];
}
複製代碼
exportButton
的響應方法負責根據imageView
中的源圖片、platform
中選擇的平臺規則和pathField
中顯示的導出路徑生成圖片並打開圖片所在的文件夾。 代碼以下:
- (IBAction)exportButtonClicked:(NSButton *)sender {
NSImage *image = _imageView.image;
NSString *platform = _platformBox.selectedCell.title;
NSString *exportPath = _pathField.stringValue;
if (!image || !platform || !exportPath) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = @"請先選擇源圖片、平臺和導出路徑";
alert.alertStyle = NSAlertStyleWarning;
[alert addButtonWithTitle:@"確認"];
[alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse returnCode) {}];
}
else {
[[NSUserDefaults standardUserDefaults] setObject:platform forKey:selectedPlatformKey];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults] setObject:exportPath forKey:exportedPathKey];
[[NSUserDefaults standardUserDefaults] synchronize];
[self generateImagesForPlatform:platform fromOriginalImage:image];
}
}
複製代碼
- (void)generateImagesForPlatform:(NSString *)platform fromOriginalImage:(NSImage *)originalImage {
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"QiConfiguration" ofType:@"plist"];
NSDictionary *configuration = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSArray<NSDictionary *> *items = configuration[platform];
NSString *directoryPath = [[_pathField.stringValue stringByAppendingPathComponent:platform] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
if ([platform containsString:@"AppIcons"]) {
[self generateAppIconsWithConfigurations:items fromOriginalImage:originalImage toDirectoryPath:directoryPath];
}
else if ([platform containsString:@"LaunchImages"]) {
[self generateLaunchImagesWithConfigurations:items fromOriginalImage:originalImage toDirectoryPath:directoryPath];
}
}
- (void)generateAppIconsWithConfigurations:(NSArray<NSDictionary *> *)configurations fromOriginalImage:(NSImage *)originalImage toDirectoryPath:(NSString *)directoryPath {
for (NSDictionary *configuration in configurations) {
NSImage *appIcon = [self generateAppIconWithImage:originalImage forSize:NSSizeFromString(configuration[@"size"])];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.png", directoryPath, configuration[@"name"]];
[self exportImage:appIcon toPath:filePath];
}
[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:directoryPath isDirectory:YES]];
}
- (void)generateLaunchImagesWithConfigurations:(NSArray<NSDictionary *> *)configurations fromOriginalImage:(NSImage *)originalImage toDirectoryPath:(NSString *)directoryPath {
for (NSDictionary *configuration in configurations) {
NSImage *launchImage = [self generateLaunchImageWithImage:originalImage forSize: NSSizeFromString(configuration[@"size"])];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.png", directoryPath, configuration[@"name"]];
[self exportImage:launchImage toPath:filePath];
}
[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:directoryPath isDirectory:YES]];
}
- (NSImage *)generateAppIconWithImage:(NSImage *)fromImage forSize:(CGSize)toSize {
NSRect toFrame = NSMakeRect(.0, .0, toSize.width, toSize.height);
toFrame = [[NSScreen mainScreen] convertRectFromBacking:toFrame];
NSImageRep *imageRep = [fromImage bestRepresentationForRect:toFrame context:nil hints:nil];
NSImage *toImage = [[NSImage alloc] initWithSize:toFrame.size];
[toImage lockFocus];
[imageRep drawInRect:toFrame];
[toImage unlockFocus];
return toImage;
}
- (NSImage *)generateLaunchImageWithImage:(NSImage *)fromImage forSize:(CGSize)toSize {
// 計算目標小圖去貼合源大圖所須要放大的比例
CGFloat wFactor = fromImage.size.width / toSize.width;
CGFloat hFactor = fromImage.size.height / toSize.height;
CGFloat toFactor = fminf(wFactor, hFactor);
// 根據所需放大的比例,計算與目標小圖同比例的源大圖的剪切Rect
CGFloat scaledWidth = toSize.width * toFactor;
CGFloat scaledHeight = toSize.height * toFactor;
CGFloat scaledOriginX = (fromImage.size.width - scaledWidth) / 2;
CGFloat scaledOriginY = (fromImage.size.height - scaledHeight) / 2;
NSRect fromRect = NSMakeRect(scaledOriginX, scaledOriginY, scaledWidth, scaledHeight);
// 生成即將繪製的目標圖和目標Rect
NSRect toRect = NSMakeRect(.0, .0, toSize.width, toSize.height);
toRect = [[NSScreen mainScreen] convertRectFromBacking:toRect];
NSImage *toImage = [[NSImage alloc] initWithSize:toRect.size];
// 繪製
[toImage lockFocus];
[fromImage drawInRect:toRect fromRect:fromRect operation:NSCompositeCopy fraction:1.0];
[toImage unlockFocus];
return toImage;
}
- (void)exportImage:(NSImage *)image toPath:(NSString *)path {
NSData *imageData = image.TIFFRepresentation;
NSData *exportData = [[NSBitmapImageRep imageRepWithData:imageData] representationUsingType:NSPNGFileType properties:@{}];
[exportData writeToFile:path atomically:YES];
}
複製代碼
上述是工程的全部代碼,代碼較多。建議有須要的同窗移步至工程源碼閱讀。
小編微信:可加並拉入《QiShare技術交流羣》。
關注咱們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公衆號)
推薦文章:
算法小專欄:「D&C思想」與「快速排序」
iOS 避免常見崩潰(二)
算法小專欄:選擇排序
iOS Runloop(一)
iOS 經常使用調試方法:LLDB命令
iOS 經常使用調試方法:斷點
iOS 經常使用調試方法:靜態分析
奇舞週刊