嗨就像我在标题上说的那样,我试图在一个与UIImage最大尺寸相匹配的正方形中绘制一个完整的UIImage。我的问题是如何使我的代码工作。什么我的代码下降是裁剪到正方形大小。我是IO的新手可以帮助。
我想要调用CGcontext的方法吗?
感谢。
- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
CGSize size = [source size];
CGFloat width = size.width;
CGFloat height = size.height;
CGSize resizedImageSize;
if (width < height) {
resizedImageSize = CGSizeMake(height, height);
}else {
resizedImageSize = CGSizeMake(width, width);
}
UIGraphicsBeginImageContext(resizedImageSize);
CGRect rect = CGRectMake(0, 0, resizedImageSize.width, resizedImageSize.height);
[source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
CGContextStrokeRect(context, rect);
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
我正在寻找的结果类型。
答案 0 :(得分:2)
看起来你比实现自己的目标更接近了。调用drawInRect时需要调整使用的矩形:保持纵横比并适合新图像的中间位置。请记住,那里使用的rect没有规定新图像的大小,传递给UIGraphicsBeginImageContext的值定义了。
- (UIImage *)squareImageFromImage:(UIImage *)image
{
// Get a square that the image will fit into
CGFloat maxSize = MAX(image.size.height, image.size.width);
CGSize squareSize = CGSizeMake(maxSize, maxSize);
// Get our offset to center the image inside our new square frame
CGFloat dx = (maxSize - image.size.width) / 2.0f;
CGFloat dy = (maxSize - image.size.height) / 2.0f;
UIGraphicsBeginImageContext(squareSize);
CGRect rect = CGRectMake(0, 0, maxSize, maxSize);
// Draw a white background and set a magenta stroke around the entire square image (debugging only?)
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetStrokeColorWithColor(context, [UIColor magentaColor].CGColor);
CGContextFillRect(context, rect);
CGContextStrokeRect(context, rect);
// Adjust the rect to be centered in our new image
rect = CGRectInset(rect, dx, dy);
[image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return squareImage;
}
采用此样本图像 Before Image, Rectangular
并为您提供这个新的方形图像 Processed Image, Square
答案 1 :(得分:2)
在Swift 3中
extension UIImage {
func squareMe() -> UIImage {
var squareImage = self
let maxSize = max(self.size.height, self.size.width)
let squareSize = CGSize(width: maxSize, height: maxSize)
let dx = CGFloat((maxSize - self.size.width) / 2)
let dy = CGFloat((maxSize - self.size.height) / 2)
UIGraphicsBeginImageContext(squareSize)
var rect = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(UIColor.clear.cgColor)
context.fill(rect)
rect = rect.insetBy(dx: dx, dy: dy)
self.draw(in: rect, blendMode: .normal, alpha: 1.0)
if let img = UIGraphicsGetImageFromCurrentImageContext() {
squareImage = img
}
UIGraphicsEndImageContext()
}
return squareImage
}
}