在ObjectiveC和Cocoa中以编程方式创建彩色气泡/圆圈

kdb*_*las 14 cocoa drawing objective-c

任何人都可以用正确的方式指导我以编程方式构建彩色气泡/圆圈吗?

我不能使用图像,因为我需要它可以是任何颜色,取决于用户交互.

我的想法可能是制作一个白色圆圈图像,然后在它上面叠加一种颜色.但是我不确定这是否有用,或者如何真正实现它.

如果有人能指出我正确的方向,我会很感激.

jos*_*rry 31

在Cocoa中绘制一些东西有几个步骤.

首先,您需要一个用于定义要绘制的对象的路径.看看这里绘制基本形状,以获得在Cocoa中创建路径的指南.您最感兴趣的是将"appendBezierPathWithOvalInRect"消息发送到"NSBezierPath"对象,这将采用一个矩形来限制您想要绘制的圆.

此代码将在坐标10,10处创建一个10x10圆:

NSRect rect = NSMakeRect(10, 10, 10, 10);
NSBezierPath* circlePath = [NSBezierPath bezierPath];
[circlePath appendBezierPathWithOvalInRect: rect];
Run Code Online (Sandbox Code Playgroud)

获得路径后,您需要为当前绘图上下文设置颜色.有两种颜色,笔划和填充; 笔划是路径的轮廓,填充是内部颜色.要设置颜色,请将"set"发送到"NSColor"对象.

这会将笔划设置为黑色,将填充设置为红色:

[[NSColor blackColor] setStroke];
[[NSColor redColor] setFill];
Run Code Online (Sandbox Code Playgroud)

现在您已经拥有自己的路径并且设置了颜色,只需填充路径然后绘制它:

[path stroke];
[path fill];
Run Code Online (Sandbox Code Playgroud)

所有这些都需要在图形上下文中完成,例如在视图的drawRect中.所有这些以及图形上下文将如下所示:

- (void)drawRect:(NSRect)rect
{
    // Get the graphics context that we are currently executing under
    NSGraphicsContext* gc = [NSGraphicsContext currentContext];

    // Save the current graphics context settings
    [gc saveGraphicsState];

    // Set the color in the current graphics context for future draw operations
    [[NSColor blackColor] setStroke];
    [[NSColor redColor] setFill];

    // Create our circle path
    NSRect rect = NSMakeRect(10, 10, 10, 10);
    NSBezierPath* circlePath = [NSBezierPath bezierPath];
    [circlePath appendBezierPathWithOvalInRect: rect];

    // Outline and fill the path
    [circlePath stroke];
    [circlePath fill];

    // Restore the context to what it was before we messed with it
    [gc restoreGraphicsState];
}
Run Code Online (Sandbox Code Playgroud)


Alm*_*bek 12

您可以使用简单UIView来创建只有参数的完美radius:

// Add framework CoreGraphics.framework
#import <QuartzCore/QuartzCore.h>

-(UIView *)circleWithColor:(UIColor *)color radius:(int)radius {
    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2 * radius, 2 * radius)];
    circle.backgroundColor = color;
    circle.layer.cornerRadius = radius;
    circle.layer.masksToBounds = YES;
    return circle;
}
Run Code Online (Sandbox Code Playgroud)

  • @tjsumpthun谢谢你,我已经更新帖子(删除autorelease),我认为人们不再使用非弧形开发. (2认同)

Mar*_*eau 11

创建一个NSView子类,将NSColor保存为ivar.在drawRect方法中,使用视图的边界创建适当大小的NSBezierPath.然后设置颜色[myColor set]并填充路径[myPath fill].你可以做更多的事情,比如设置透明度,边框等等,但除非你有特定的问题,否则我会把它留给文档.

要使用NSView子类,只需将视图对象拖到您的nib上,然后在IB的检查器中的自定义类中选择子类的名称.您还需要在控制器中为其设置插座,以便根据需要更改颜色.


小智 7

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(c, 40, 0, 255, 0.1);
    CGContextSetRGBStrokeColor(c, 0, 40, 255, 0.5);

   // Draw a green solid circle
    CGContextSetRGBFillColor(c, 0, 255, 0, 1);
    CGContextFillEllipseInRect(c, CGRectMake(100, 100, 25, 25));
Run Code Online (Sandbox Code Playgroud)