Before anyone points me at this post, I've already tried it, and it doesn't work for me. I am trying to generate a black and white snapshot of an MKMapView. The quality, however, is terribly low on the iPhone 4. Here is my code. Anyone have any suggestions?
- (void)mapSnapShotWithMapView:(MKMapView *)_mapView {
CGSize s 开发者_JS百科= CGSizeMake(_mapView.bounds.size.width, _mapView.bounds.size.height);
UIGraphicsBeginImageContextWithOptions(s, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[_mapView layer] renderInContext:ctx];
UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
ctx = CGBitmapContextCreate(nil, s.width, s.height, 8, s.width, colorSpace, kCGImageAlphaNone);
CGContextSetShouldAntialias(ctx, YES);
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
CGContextDrawImage(ctx, CGRectMake(0, 0, s.width, s.height), thumb.CGImage);
CGImageRef bwImage = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];
[imageView setImage:[UIImage imageWithCGImage:bwImage]];
CGImageRelease(bwImage);
[self.view addSubView:imageView];
[imageView release];
}
I figured it out thanks to this post. It was not using the iPhone's native resolution, even though 0.0f as the last parameter of UIGraphicsBeginImageContextWithOptions should do this. Regardless, here is the updated code:
- (void)mapSnapShotWithMapView:(MKMapView *)_mapView {
CGSize s = _mapView.bounds.size;
CGFloat scale = 1.0;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
scale = [[UIScreen mainScreen] scale];
s = CGSizeApplyAffineTransform(s, CGAffineTransformMakeScale(scale, scale));
}
UIGraphicsBeginImageContextWithOptions(s, NO, 1.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, scale, scale);
[[_mapView layer] renderInContext:ctx];
UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
ctx = CGBitmapContextCreate(nil, s.width, s.height, 8, s.width, colorSpace, kCGImageAlphaNone);
CGContextSetShouldAntialias(ctx, YES);
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
CGContextDrawImage(ctx, CGRectMake(0, 0, s.width, s.height), thumb.CGImage);
CGImageRef bwImage = CGBitmapContextCreateImage(ctx);
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width/2, s.height/2)];
[imageView setImage:[UIImage imageWithCGImage:bwImage]];
CGImageRelease(bwImage);
[self.view addSubview:imageView];
[imageView release];
}
精彩评论