使用图像
为了便于操作对象,iOS中定义了图像类:
UIImage(UIKit框架中定义的图像类)
CGImage(在Core Graphics框架(或Quartz 2D)中定义的图像类)
CIImage(Core Image)
以上三者之间可以相互转化。
创建图像的四种方式
1.从资源文件中直接加载
2.从应用程序沙盒目录加载
3.从云服务器端获取
4.从设备图片库选取或从照相机抓取
Swift代码
import UIKit
let FILE_NAME = "WeChat_1468557469.png"
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//把资源文件中的图片复制到沙河中document目录下
self.createEditableCopyOfDatabaseIfNeeded()
self.imageView.image = UIImage(named:"WeChat_1468557469.png")
}
func createEditableCopyOfDatabaseIfNeeded() {
// NSFileManager采用单例设计模式
let fileManager = NSFileManager.defaultManager()
let writalbeDBPath = applicationDocumentsDirectoryFile()
let dbexits = fileManager.fileExistsAtPath(writalbeDBPath)
//如果文件不存在,则copy一个图文到沙盒中
if !dbexits {
}
}
func applicationDocumentsDirectoryFile() -> String {
let documentDirectorys:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documetDirectory = documentDirectorys[0] as!String
let path = documetDirectory.stringByAppendingString(FILE_NAME)
return path
}
@IBAction func loadBundle(sender: AnyObject) {
let path = NSBundle.mainBundle().pathForResource("WeChat_1468557469", ofType: "png")
var image = UIImage(contentsOfFile: path!)
self.imageView.image = UIImage(named:"WeChat_1468557469.png")
}
@IBAction func loadSandbox(sender: AnyObject) {
let path = self.applicationDocumentsDirectoryFile()
self.imageView.image = UIImage(contentsOfFile:path)
}
@IBAction func loadWebService(sender: AnyObject) {
NSLog("从云服务器中加载图片")
}
}
OC代码
//对文件进行预处理,判断在Documents目录下是否存在plist文件,如果不存在则从资源目录下复制一个。
-(void)createEditableCopyOfDatabaseIfNeeded
{
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *writableDBPath=[self applicationDocumentsDirectoryFile];
BOOL dbexits=[fileManager fileExistsAtPath:writableDBPath];
if (!dbexits) {
NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Contacts.plist"];
NSError *error;
BOOL success=[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0,@"错误写入文件:‘%@’",[error localizedDescription]);
}
}
}
//获取放置在沙箱Documents目录下的文件的完整路径
-(NSString *)applicationDocumentsDirectoryFile
{
NSString *documentDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path=[documentDirectory stringByAppendingPathComponent:@"Contacts.plist"];
return path;
}