Ответ 1
В примере кода Apple они настраивают геометрию графического контекста в соответствии с геометрией слоя перед вызовом renderInContext:
.
Они имеют дело с окном, но похоже, что код должен работать с любым представлением с некоторыми незначительными изменениями.
Я не пробовал это строить, но вот моя попытка изменить код Apple для работы с любым видом.
- (UIImage*)imageFromView:(UIView *)view
{
// Create a graphics context with the target size
// On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
// On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
CGSize imageSize = [view bounds].size;
if (NULL != UIGraphicsBeginImageContextWithOptions)
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
else
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the view anchor point
CGContextTranslateCTM(context, [view center].x, [view center].y);
// Apply the view transform about the anchor point
CGContextConcatCTM(context, [view transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
-[view bounds].size.width * [[view layer] anchorPoint].x,
-[view bounds].size.height * [[view layer] anchorPoint].y);
// Render the layer hierarchy to the current context
[[view layer] renderInContext:context];
// Restore the context
CGContextRestoreGState(context);
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}