Tôi cần chụp lại UIView và tất cả các bản xem phụ của nó thành UIImage. Vấn đề là một phần của xem là tắt màn hình, vì vậy tôi không thể sử dụng chức năng chụp màn hình, và khi tôi cố gắng sử dụng chức năng UIGraphicsGetImageFromCurrentImageContext(), nó dường như không nắm bắt các subviews là tốt. Nếu nó được chụp các cuộc phỏng vấn và tôi chỉ làm điều gì đó sai? Nếu không, có cách nào khác để hoàn thành việc này không?Cần chụp UIView thành UIImage, bao gồm tất cả các bản xem trước
Trả lời
Bạn có nghĩa là
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
không hoạt động? Tôi chắc rằng nó nên ...
Đó là cách đúng đắn để đi:
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Phương pháp này là một phương pháp mở rộng cho lớp UIImage, và nó cũng sẽ chăm sóc làm cho ngoại hình ảnh tốt trên mọi thiết bị có độ phân giải cao trong tương lai.
Thực sự hoạt động !!! – AlexeyVMP
Đã lưu thời gian của tôi :) Cảm ơn –
Dưới đây là một phiên bản 2.x Swift rằng nên làm việc nếu bạn lần đầu tiên tạo ra một mảng của UIViews để làm phẳng:
// Flattens <allViews> into single UIImage
func flattenViews(allViews: [UIView]) -> UIImage? {
// Return nil if <allViews> empty
if (allViews.isEmpty) {
return nil
}
// If here, compose image out of views in <allViews>
// Create graphics context
UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)
// Draw each view into context
for curView in allViews {
curView.drawViewHierarchyInRect(curView.frame, afterScreenUpdates: false)
}
// Extract image & end context
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Return image
return image
}
tôi đoán rằng bởi vì mỗi 'UIView' là layer-based gọi '- [CALayer drawInContext: viewContext] 'có thể giúp. –