OLD | NEW |
(Empty) | |
| 1 // Copyright 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "skia/ext/skia_utils_ios.h" |
| 6 |
| 7 #import <UIKit/UIKit.h> |
| 8 |
| 9 #include "base/logging.h" |
| 10 #include "base/mac/scoped_cftyperef.h" |
| 11 #include "third_party/skia/include/utils/mac/SkCGUtils.h" |
| 12 |
| 13 namespace gfx { |
| 14 |
| 15 SkBitmap UIImageToSkBitmap(UIImage* image, CGSize size, bool is_opaque) { |
| 16 SkBitmap bitmap; |
| 17 if (!image) |
| 18 return bitmap; |
| 19 |
| 20 bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width, size.height); |
| 21 if (!bitmap.allocPixels()) |
| 22 return bitmap; |
| 23 |
| 24 bitmap.setIsOpaque(is_opaque); |
| 25 void* data = bitmap.getPixels(); |
| 26 |
| 27 // Allocate a bitmap context with 4 components per pixel (BGRA). Apple |
| 28 // recommends these flags for improved CG performance. |
| 29 #define HAS_ARGB_SHIFTS(a, r, g, b) \ |
| 30 (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \ |
| 31 && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b)) |
| 32 #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) |
| 33 base::mac::ScopedCFTypeRef<CGColorSpaceRef> color_space( |
| 34 CGColorSpaceCreateDeviceRGB()); |
| 35 base::mac::ScopedCFTypeRef<CGContextRef> context( |
| 36 CGBitmapContextCreate(data, size.width, size.height, 8, size.width*4, |
| 37 color_space, |
| 38 kCGImageAlphaPremultipliedFirst | |
| 39 kCGBitmapByteOrder32Host)); |
| 40 #else |
| 41 #error We require that Skia's and CoreGraphics's recommended \ |
| 42 image memory layout match. |
| 43 #endif |
| 44 #undef HAS_ARGB_SHIFTS |
| 45 |
| 46 DCHECK(context); |
| 47 if (!context) |
| 48 return bitmap; |
| 49 |
| 50 // UIGraphicsPushContext be called from the main thread. |
| 51 // TODO(rohitrao): We can use CG to make this thread safe, but the mac code |
| 52 // calls setCurrentContext, so it's similarly limited to the main thread. |
| 53 DCHECK([NSThread isMainThread]); |
| 54 UIGraphicsPushContext(context); |
| 55 [image drawInRect:CGRectMake(0, 0, size.width, size.height) |
| 56 blendMode:kCGBlendModeCopy |
| 57 alpha:1.0]; |
| 58 UIGraphicsPopContext(); |
| 59 |
| 60 return bitmap; |
| 61 } |
| 62 |
| 63 UIImage* SkBitmapToUIImageWithColorSpace(const SkBitmap& skia_bitmap, |
| 64 CGColorSpaceRef color_space) { |
| 65 if (skia_bitmap.isNull()) |
| 66 return nil; |
| 67 |
| 68 // First convert SkBitmap to CGImageRef. |
| 69 base::mac::ScopedCFTypeRef<CGImageRef> cg_image( |
| 70 SkCreateCGImageRefWithColorspace(skia_bitmap, color_space)); |
| 71 |
| 72 // Now convert to UIImage. |
| 73 // TODO(rohitrao): Gotta incorporate the scale factor somewhere! |
| 74 return [UIImage imageWithCGImage:cg_image.get()]; |
| 75 } |
| 76 |
| 77 } // namespace gfx |
OLD | NEW |