UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
[picker release];
สร้าง object ของ UIImagePickerController ออกมา จากนั้นกำหนด delegate ให้มัน และแสดง picker ออกมาผ่าน modal view เท่านั้นเอง ซึ่งระหว่างก่อนที่จะแสดง picker ขึ้นมานั้น จะเห็นว่ามี 2 จุดที่เราต้องทำอะไรบางอย่างได้แก่จุดแรก
picker.allowsEditing = YES;
เป็นการบอกว่าหลังจากถ่ายรูปเสร็จแล้ว จะให้มีการแก้ไขรูปต่อหรือเปล่า เช่นการย่อ ขยาย เป็นต้น
และจุดที่สองคือ
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
เป็นการ กำหนดแหล่งที่มาของรูป จากตัวอย่างเป็นการกำหนดแหล่งที่มาของรูปคือ กล้องนั่นเอง ซึ่งนอกจากกำหนดแหล่งที่มาเป็นกล้องได้แล้ว เรายังกำหนดแหล่งที่มาได้อีก 2 แบบ ที่เป็นการเลือกรูปจากในเครื่องของเราเอง ได้แก่
UIImagePickerControllerSourceTypePhotoLibrary
UIImagePickerControllerSourceTypeSavedPhotosAlbum
UIImagePickerControllerSourceTypeSavedPhotosAlbum
จากนั้นอย่าลืม implement delegate method ของ picker ด้วย ดังนี้
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), self);
[picker dismissModalViewControllerAnimated:YES];
}
หลัง จากเราเลือก รูปเสร็จแล้ว (รวมถึงการถ่ายรูปเสร็จแล้วด้วย) method นี้จะทำงานทันที เราจะได้ reference ของ image จากนั้นก็ทำการ save ทันที โดยกำหนด selector ให้ทำงานหลังจากการ save เสร็จสิ้นไว้ด้วย หน้าตาดังนี้
- (void) image: (UIImage*) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
NSString *str = @"Saved";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Saved." message:str delegate:self cancelButtonTitle:nil otherButtonTitles: @"OK", nil];
[alert show];
NSLog(@"error = %@", error);
}
และอีก 1 delegate method ที่จะทำงานเมื่อเรายกเลิกการเลือกรูป ดังนี้
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
เท่านี้ก็เรียบร้อย
UPDATE:
ยัง ไม่เรียบร้อย สิ่งที่ควรเพิ่มเข้ามาสำหรับ application ที่ต้องใช้/สามารถใช้กล้องถ่ายรูปได้ก็คือการตรวจสอบว่าอุปกรณ์ที่ application ทำงานอยู่นั้นมี resource อยู่จริงหรือไม่ เช่นมี photo library หรือมีกล้องพร้อมใช้งานไหม โดยใช้ class method ของ UIImagePickerController ชื่อ isSourceTypeAvailable ดังนี้
if (![UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera]) {
// do something
}
เท่านี้ก็เรียบร้อย
0 comments:
Post a Comment