西海岸より

つらつらざつざつと

UIAlertViewのキャプチャー画像を出力

UIAlertViewのキャプチャ画像を取得するコードメモ。

  • 出力例 (本当は透過あり)


  • AlertCaptureViewController.h
#import <UIKit/UIKit.h>

@interface AlertCaptureViewController : UIViewController

@property (nonatomic, retain) UIAlertView *alertView;

@end
  • AlertCaptureViewController.m
#import "AlertCaptureViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation AlertCaptureViewController

- (NSString *)saveBaseDir {
  NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask,
                                                       YES);  
  return [array objectAtIndex:0];
}

- (BOOL) captureView:(UIView *)aview name:(NSString *)filename {
  
  UIGraphicsBeginImageContext(aview.frame.size);
	[aview.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
  
  NSString *saveFileName = filename;
  NSString *saveFilePath = [[self saveBaseDir] stringByAppendingPathComponent:saveFileName];
  
  NSData *data = UIImagePNGRepresentation(viewImage);
  NSError *error = nil;
  [data writeToFile:saveFilePath options:NSDataWritingAtomic error:&error];
  if (error) {
    NSLog(@"Error png file:%@ error=%@", saveFileName, [error description]);
    return NO;
  } else {
    NSLog(@"Success png file:%@", saveFileName);
    return YES;
  }
}

- (void)stepCapture {
  [self captureView:self.alertView name:@"output.png"];
}

- (void)showAlertAndCapture {
  UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"タイトル"
                                               message:@"メッセージ"
                                              delegate:nil
                                     cancelButtonTitle:nil
                                     otherButtonTitles:@"閉じる", nil];
  [av show];
  [self setAlertView:av];
  [av release];
  
  [self performSelector:@selector(stepCapture)
           withObject:nil
           afterDelay:0.7f];
}

- (void)viewDidAppear:(BOOL)animated
{
  [super viewDidAppear:animated];
  [self showAlertAndCapture];
}


#pragma mark -

- (void)dealloc {
  [self setAlertView:nil];
  [super dealloc];
}

@synthesize alertView;

@end