CoreGraphicsを使用してカスタム描画を行いたいです。ビューに線形グラデーションが必要ですが、このビューは角の丸い長方形であるため、グラデーションも角度を付けて丸くしたいと思います。下の画像で私が達成したいことを見ることができます:
では、これをCoreGraphicsやその他のプログラムによる簡単な方法で実装することは可能ですか?ありがとうございました。
CoreGraphicsを使用してカスタム描画を行いたいです。ビューに線形グラデーションが必要ですが、このビューは角の丸い長方形であるため、グラデーションも角度を付けて丸くしたいと思います。下の画像で私が達成したいことを見ることができます:
では、これをCoreGraphicsやその他のプログラムによる簡単な方法で実装することは可能ですか?ありがとうございました。
そのためのAPIはないと思いますが、たとえば(N+1)x(N+1)
サイズのビットマップコンテキストで最初に放射状のグラデーションを描画し、次に画像をコンテキストから左右のサイズ変更可能な画像に変換すると、同じ効果を得ることができます。キャップをに設定しN
ます。
擬似コード:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(N+1,N+1), NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
// <draw the gradient into 'context'>
UIImage* gradientBase = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage* gradientImage = [gradientBase resizableImageWithCapInsets:UIEdgeInsetsMake(0,N,0,N)];
画像を垂直方向にも拡大縮小したい場合は、キャップをに設定するだけですUIEdgeInsetsMake(N,N,N,N)
。
いくつかのことが明らかではなかったので、このテクニックのサンプルコードをさらに追加したいと思います。多分それは誰かのために役立つでしょう:
たとえば、カスタムビュークラスがあり、そのdrawRect:
メソッドに次のように配置するとします。
// Defining the rect in which to draw
CGRect drawRect=self.bounds;
Float32 gradientSize=drawRect.size.height; // The size of original radial gradient
CGPoint center=CGPointMake(0.5f*gradientSize,0.5f*gradientSize); // Center of gradient
// Creating the gradient
Float32 colors[4]={0.f,1.f,1.f,0.2f}; // From opaque white to transparent black
CGGradientRef gradient=CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceGray(), colors, nil, 2);
// Starting image and drawing gradient into it
UIGraphicsBeginImageContextWithOptions(CGSizeMake(gradientSize, gradientSize), NO, 1.f);
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextDrawRadialGradient(context, gradient, center, 0.f, center, center.x, 0); // Drawing gradient
UIImage* gradientImage=UIGraphicsGetImageFromCurrentImageContext(); // Retrieving image from context
UIGraphicsEndImageContext(); // Ending process
gradientImage=[gradientImage resizableImageWithCapInsets:UIEdgeInsetsMake(0.f, center.x-1.f, 0.f, center.x-1.f)]; // Leaving 2 pixels wide area in center which will be tiled to fill whole area
// Drawing image into view frame
[gradientImage drawInRect:drawRect];
それで全部です。また、アプリの実行中にグラデーションを変更しない場合は、awakeFromNib
メソッドの最後の行を除くすべてを配置してからdrawRect:
、gradientImageをビューのフレームに描画するだけです。gradientImage
また、この場合は保持することを忘れないでください。