如何通过AppleScript创建带分层缩放图标的自定义文件夹图标
AppleScript实现自定义叠加式文件夹图标
下面是完整的AppleScript代码,实现选择目标文件夹与应用/图片文件,将图标缩放至原尺寸60%后叠加到文件夹图标指定位置,最终替换文件夹图标:
use framework "Foundation" use framework "AppKit" use scripting additions -- 1. 选择目标文件夹 set targetFolder to choose folder with prompt "请选择要修改图标的文件夹" set targetFolderPath to POSIX path of targetFolder -- 2. 选择应用或图片文件 set sourceFile to choose file with prompt "请选择要叠加的应用或图片文件" of type {"public.image", "com.apple.application-bundle"} set sourceFilePath to POSIX path of sourceFile -- 3. 获取文件夹原始图标 set workspace to current application's NSWorkspace's sharedWorkspace() set folderImage to workspace's iconForFile:targetFolderPath -- 确保文件夹图标使用标准尺寸(512x512) folderImage's setSize:{512, 512} -- 4. 获取并缩放源图标 set sourceImage to workspace's iconForFile:sourceFilePath if sourceImage is missing value then try -- 针对纯图片文件直接读取 set sourceImage to current application's NSImage's alloc()'s initWithContentsOfFile:sourceFilePath on error display alert "错误" message "无法获取所选文件的图标" error number -128 end try end if -- 计算60%缩放后的尺寸 set originalSize to sourceImage's size() set scaledWidth to (originalSize's width) * 0.6 set scaledHeight to (originalSize's height) * 0.6 sourceImage's setSize:{scaledWidth, scaledHeight} -- 5. 设置叠加位置(示例:右下角,距离边缘20px) set overlayX to 512 - scaledWidth - 20 set overlayY to 20 -- 6. 合成新图标 set compositeImage to current application's NSImage's alloc()'s initWithSize:{512, 512} compositeImage's lockFocus() -- 绘制文件夹背景图标 folderImage's drawAtPoint:{0, 0} fromRect:(current application's NSZeroRect) operation:(current application's NSCompositeSourceOver) fraction:1.0 -- 绘制缩放后的叠加图标 sourceImage's drawAtPoint:{overlayX, overlayY} fromRect:(current application's NSZeroRect) operation:(current application's NSCompositeSourceOver) fraction:1.0 compositeImage's unlockFocus() -- 7. 将合成图标设置为文件夹图标 set success to workspace's setIcon:compositeImage forFile:targetFolderPath options:0 if success then display alert "成功" message "文件夹图标已修改完成" else display alert "错误" message "无法设置文件夹图标" end if
关键代码说明
- 框架依赖:通过
use framework引入Foundation和AppKit,这是实现图标合成、系统文件交互的核心基础。 - 图标获取:用
NSWorkspace的iconForFile:方法获取系统图标,纯图片文件则直接通过NSImage读取内容。 - 缩放处理:读取源图标原始尺寸后,计算60%比例的新尺寸并应用到图标对象。
- 图标合成:创建空白画布,先绘制文件夹背景图标,再在指定坐标绘制缩放后的叠加图标,通过
lockFocus()和unlockFocus()完成绘制流程。 - 图标应用:调用
NSWorkspace的setIcon:forFile:options:方法,将合成后的图标替换目标文件夹的默认图标。
自定义调整指南
- 修改缩放比例:把代码中的
0.6改成对应数值即可(比如0.5代表50%缩放)。 - 调整叠加位置:修改
overlayX和overlayY的计算逻辑:- 左上角:
set overlayX to 20、set overlayY to 512 - scaledHeight - 20 - 居中:
set overlayX to (512 - scaledWidth) / 2、set overlayY to (512 - scaledHeight) / 2
- 左上角:
内容的提问来源于stack exchange,提问作者Phedinopsis brazzae
相关产品推荐
相关产品推荐

