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.
5 #include "skia/ext/skia_utils_ios.h"
7 #import <UIKit/UIKit.h>
9 #include "base/logging.h"
10 #include "base/mac/scoped_cftyperef.h"
11 #include "third_party/skia/include/utils/mac/SkCGUtils.h"
15 SkBitmap CGImageToSkBitmap(CGImageRef image, CGSize size, bool is_opaque) {
20 bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width, size.height);
21 if (!bitmap.allocPixels())
24 bitmap.setIsOpaque(is_opaque);
25 void* data = bitmap.getPixels();
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,
38 kCGImageAlphaPremultipliedFirst |
39 kCGBitmapByteOrder32Host));
41 #error We require that Skia's and CoreGraphics's recommended \
42 image memory layout match.
44 #undef HAS_ARGB_SHIFTS
50 CGRect imageRect = CGRectMake(0.0, 0.0, size.width, size.height);
51 CGContextSetBlendMode(context, kCGBlendModeCopy);
52 CGContextDrawImage(context, imageRect, image);
57 UIImage* SkBitmapToUIImageWithColorSpace(const SkBitmap& skia_bitmap,
59 CGColorSpaceRef color_space) {
60 if (skia_bitmap.isNull())
63 // First convert SkBitmap to CGImageRef.
64 base::mac::ScopedCFTypeRef<CGImageRef> cg_image(
65 SkCreateCGImageRefWithColorspace(skia_bitmap, color_space));
67 // Now convert to UIImage.
68 return [UIImage imageWithCGImage:cg_image.get()
70 orientation:UIImageOrientationUp];