UIColorに基づいて動的に1x1UIImageを作成したいと思います。
これはQuartz2dですぐに実行できると思います。そして、基本を理解しようとしているドキュメントをじっくり考えています。ただし、潜在的な落とし穴がたくさんあるようです。つまり、物ごとのビット数とバイト数を正しく識別できない、正しいフラグを指定しない、未使用のデータを解放しないなどです。
Quartz 2d(または別のより簡単な方法)でこれを安全に行うにはどうすればよいですか?
UIColorに基づいて動的に1x1UIImageを作成したいと思います。
これはQuartz2dですぐに実行できると思います。そして、基本を理解しようとしているドキュメントをじっくり考えています。ただし、潜在的な落とし穴がたくさんあるようです。つまり、物ごとのビット数とバイト数を正しく識別できない、正しいフラグを指定しない、未使用のデータを解放しないなどです。
Quartz 2d(または別のより簡単な方法)でこれを安全に行うにはどうすればよいですか?
これにはCGContextSetFillColorWithColor
とを使用できます。CGContextFillRect
迅速
extension UIImage {
class func image(with color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Swift3
extension UIImage {
class func image(with color: UIColor) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Objective-C
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Matt Stephen のコードに基づく別のオプションを次に示します。サイズ変更可能な無地の画像を作成して、再利用したり、サイズを変更したりできます (背景に使用するなど)。
+ (UIImage *)prefix_resizeableImageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 3.0f, 3.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)];
return image;
}
UIImage カテゴリに入れ、プレフィックスを変更します。
わかりました、これはまさにあなたが望むものではありませんが、このコードは線を引きます。ポイントを作るためにそれを適応させることができます。または、少なくともそこから少しの情報を入手してください。
画像を 1x1 にするのは少し奇妙に思えます。ストロークは線に乗るので、0.5 で幅 1.0 のストロークが機能するはずです。ただ遊んでください。
- (void)drawLine{
UIGraphicsBeginImageContext(CGSizeMake(320,300));
CGContextRef ctx = UIGraphicsGetCurrentContext();
float x = 0;
float xEnd = 320;
float y = 300;
CGContextClearRect(ctx, CGRectMake(5, 45, 320, 300));
CGContextSetGrayStrokeColor(ctx, 1.0, 1.0);
CGContextSetLineWidth(ctx, 1);
CGPoint line[2] = { CGPointMake(x,y), CGPointMake(xEnd, y) };
CGContextStrokeLineSegments(ctx, line, 2);
UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}