ios - 如何创建带边框的圆形图像(UIGraphics)?

标签 ios objective-c uigraphicscontext

如何创建带边框的圆形图像(UIGraphics)?

附言我需要画一幅画。

viewDidLoad 中的代码:

NSURL *url2 = [NSURL URLWithString:@"http://images.ak.instagram.com/profiles/profile_55758514_75sq_1399309159.jpg"];
NSData *data2 = [NSData dataWithContentsOfURL:url2];
UIImage *profileImg = [UIImage imageWithData:data2];

UIGraphicsEndImageContext();
// Create image context with the size of the background image.
UIGraphicsBeginImageContext(profileImg.size);
[profileImg drawInRect:CGRectMake(0, 0, profileImg.size.width, profileImg.size.height)];

// Get the newly created image.
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

// Release the context.
UIGraphicsEndImageContext();

// Set the newly created image to the imageView.
self.imageView.image = result;

最佳答案

听起来您想将图像剪裁成一个圆圈。这是一个例子:

static UIImage *circularImageWithImage(UIImage *inputImage,
    UIColor *borderColor, CGFloat borderWidth)
{

    CGRect rect = (CGRect){ .origin=CGPointZero, .size=inputImage.size };

    UIGraphicsBeginImageContextWithOptions(rect.size, NO, inputImage.scale); {

        // Fill the entire circle with the border color.
        [borderColor setFill];
        [[UIBezierPath bezierPathWithOvalInRect:rect] fill];

        // Clip to the interior of the circle (inside the border).
        CGRect interiorBox = CGRectInset(rect, borderWidth, borderWidth);
        UIBezierPath *interior = [UIBezierPath bezierPathWithOvalInRect:interiorBox];
        [interior addClip];

        [inputImage drawInRect:rect];

    }

    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outputImage;
}

结果:

example before/after

关于ios - 如何创建带边框的圆形图像(UIGraphics)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25448825/

相关文章:

ios - "Inverse"来自 NSAttributedString 的 UIImage

ios - 在 Swift 中画线

objective-c - 在沙盒中从 objective-c /swift 重置 Finder

objective-c - 从子类访问父类(super class)属性

swift - 使用子类值中的 uislider 更改线宽

ios - 在移动它的 SKSpriteNode 时将 Velocity 添加到 SKPhysicsBody

objective-c - 导入框架时 Xcode "Could Not Build Module MobileCoreServices.h"

ios - 如何使用自动布局获取 View 的实际大小?

iphone - TableViewDataSource 文件的运行时错误已分离

cocoa-touch - 关闭模态视图 Controller 后重新加载 gridView 数据时出现问题