UIImageでグラデーションしたい(その1)

結論からいうと、まだできてませんがwww
とりあえず画面いっぱいに設定したUIImageViewに色を設定してみるコード。

  int width = 320;
  int height = 480;
  int bytesPerRow = 4 * width;
  unsigned char pixel[bytesPerRow * height];
  
  int n;
  unsigned char *ptr = pixel;
  for(int j=0;j<height;j++){
    for(int i=0;i<width;i++){
      *ptr++ = 128; //r
      *ptr++ = 0; //g
      *ptr++ = 255; //b
      *ptr++ = 255; //a      
    }
  }
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  CGContextRef ctx = CGBitmapContextCreate(pixel, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
  
  CGImageRef newCGImg = CGBitmapContextCreateImage(ctx);
  CGContextRelease(ctx);
  CGColorSpaceRelease(colorSpace);
  imageView.image = [UIImage imageWithCGImage:newCGImg];

[参考]

こんな感じ。

疑問点。

  • rgbaのaの値を変更すると透過してくれるのかと思いつつ、やってみるとグレーになってしまう。これは何故なんだろ?
  • kCGImageAlphaPremultipliedLast と kCGImageAlphaLast の違いは?


疑問点は後回しにして簡単なのやってみたw

for文のところをこのように変更。

  for(int j=0;j<height;j++){
    for(int i=0;i<width;i++){
      *ptr++ = 128 * i/width * j/height; //r
      *ptr++ = 0 * i/width * j/height; //g
      *ptr++ = 255 * i/width * j/height; //b
      *ptr++ = 255; //a
    }
  }

結果はこんなん。

うーんマンダム。