草庐IT

ios - 是什么导致 CGContextAddArc 出现这种边缘情况?

coder 2024-01-24 原文

我通过使用 iOS Core Graphics 在圆的周边绘制圆弧来创建 View 。计算点中心,将其存储在数组中,并在呈现到屏幕之前使用 CGContextAddArc 检索。我对用于绘制周边点的方法充满信心,这些点可能是 [A] 轮廓,[B] 填充一种颜色,[C] 交替填充和轮廓,以及 [D] 填充如图所示的五种颜色序列。

但是,如果将中心点添加到数组中,则绘制在周边上的最后一个点的属性会发生变化。

证明这种情况的最简单方法是绘制外围点,并添加 [E] 小中心点 [F] 大中心点和 [G] 两个中心点;在每种情况下,中心的小点和大点都应填充为绿色。对于 [H],当两个居中点的轮廓未被填充时,也会出现问题。

我已经学习 Core Graphics 一个月了,需要帮助来确定导致这种情况的边缘条件。我真的很欢迎更有经验的核心图形程序员的见解。谢谢。

这里是实现代码;首先,初始化 View 设置的方法。

- (void)ViewSettings_WaitView {
    sectors         = 80;   // number of dots on perimeter
    limit           = sectors;

    uberRadius      = 52;   // radius of large circle perimeter
    dotRadius       = 4;    // radius of dots on large circle perimeter
    dotsFilled      = FALSE;    // fill every with colour or outline
    oneColour       = FALSE;    // every colour or one colour
    alternateDots   = FALSE;    // alternately filled and outlined

    ringDot         = 64;   // 64:show 0:hide
    ringDotFilled   = TRUE; // fill or outlined    
    centreDot       = 26;       // 26:show 0:hide
    centreDotFilled = FALSE;    // fill or outlined

    [self centreReference];     // set up arc drawing to start from 12 o'clock position
    [self selectZone];          // emulate 1-of-5 colours selected in GlobalView
} 

这是绘制这些图像的代码

- (void)drawCircle                  {
    context          = UIGraphicsGetCurrentContext();          // Get the Graphics Context
    CGContextSetLineWidth(context, 0.5);                       // Set the circle outerline-width

    dotPosition                    = CGPointMake(uberX,uberY); // centre point for ring dot and centre dot

    // create ring dot (larger centre dot)

    if (ringDot     != 0) {
        iOSCircle *newCircle       = [[iOSCircle alloc] init]; // Create a new iOSCircle Object
        newCircle.circleRadius     = ringDot;                  // ringDot radius
        newCircle.circleCentre     = dotPosition;              // place ringDot on the frame
        [totalCircles addObject:newCircle];                    // add to the circle Array
        [self setNeedsDisplay];                                // update the view

        NSLog(@"ringDot added:%@ radius: %f", NSStringFromCGPoint(dotPosition), ringDot);
    }

    // create centre dot (smaller centre dot)

    if (centreDot    != 0) {
        iOSCircle *newCircle       = [[iOSCircle alloc] init]; // Create a new iOSCircle Object
        newCircle.circleRadius     = centreDot;                // ringDot radius
        newCircle.circleCentre     = dotPosition;              // place ringDot on the frame
        [totalCircles addObject:newCircle];                    // add to the circle Array
        [self setNeedsDisplay];                                // update the view

        NSLog(@"centreDot added:%@ radius: %f", NSStringFromCGPoint(dotPosition), centreDot);
    }

    // create sector dots (on perimeter of the arc)

    for (dotCount   = 1; dotCount < limit+1; dotCount++)
    {
        iOSCircle *newCircle    = [[iOSCircle alloc] init];    // Create a new iOSCircle Object
        newCircle.circleRadius  = dotRadius;

            [self newCentre];                                  // create a new x and y point for each sector dot

        dotPosition             = CGPointMake(x,y);            // create each sector dot
        newCircle.circleCentre  = dotPosition;                 // place each dot on the frame
            [totalCircles addObject:newCircle];                // add to the circle Array
            [self setNeedsDisplay];                            // update the view

        NSLog(@"Dot %i %@", dotCount, NSStringFromCGPoint(dotPosition));
    }

    dotCount = 1;
    for (iOSCircle *circle in totalCircles) {                  // Loop through array and retrieve dot dimensions
        CGContextAddArc(context, circle.circleCentre.x, circle.circleCentre.y, circle.circleRadius, 0.0, M_PI * 2.0, YES);

            [self renderSectorDots];                           // render dots to view

    dotCount++;

    }    
    if (ringDot    != 0) {
        NSLog(@"add ringDot %@ radius: %f", NSStringFromCGPoint(dotPosition), ringDot);

        [self renderRingDot];
    }
    if (centreDot    != 0) {
        NSLog(@"add centreDot %@ radius: %f", NSStringFromCGPoint(dotPosition), centreDot);

        [self renderCentreDot];
    }
} 

以及绘制中心点的方法(环点类似)

- (void)renderCentreDot {
    switch (centreDotFilled) {
        case 1:
            colourIndex = selectedZone;
            [self whatColour];
            break;
        default:
            [self dotOutline];
            break;
    }
} 

- (void)whatColour {
    switch (colourIndex) {
        case 1:
            // Fill the circle with cyan
            [self paintCyan];
            break;
        case 2:
            // Fill the circle with red
            [self paintRed];
            break;
        case 3:
            // Fill the circle with yellow
            [self paintYellow];
            break;
        case 4:
            // Fill the circle with magenta
            [self paintMagenta];
            break;
        case 5:
            // Fill the circle with green
            [self paintGreen];
            break;
        default:
            break;
    }
}

- (void)dotOutline {
    CGContextStrokePath(context);                     // draw outerline only
} 

- (void)paintGreen {
    CGContextSetFillColorWithColor(context, [[UIColor greenColor] CGColor]);
    CGContextDrawPath(context, kCGPathFillStroke);    // fill with outerline-colour
    }

最后是计算扇形点新中心的方法

- (void)newCentre  {
    dotAngle    = dotAngle + uberAngle;
    x           = uberX + (uberRadius * 2 * cos(dotAngle));
    y           = uberY + (uberRadius * 2 * sin(dotAngle));    
//    NSLog(@"%i %f %f %f", dotCount, dotAngle, endAngle, uberAngle);
}

以及初始化中心参数并从12点钟位置开始绘制的方法

- (void)centreReference { 

    uberX     = 160; 
    uberY     = 240; 
    uberAngle = (2.0 * PI) / sectors; 

    dotAngle  = PI * -0.5;             // start drawing 0.5 PI radians before 3 o'clock
    endAngle  = PI * 1.5;              // stop drawing 1.5 PI radians after 3 o'clock 

    NSLog(@"%f %f %f %f", uberX, ringY, uberRadius, uberAngle); 

最佳答案

您有 80 个外圈和 0、1 或 2 个内圈。所有这些圆都存储在一个名为 totalCircles 的数组中,内部圆存储在数组的前面。因此,如果您有两个内圈,则 totalCircles 有 82 个元素。

问题是您只绘制了前 80 个圆:两个内圆和 78 个外圆。

然后您尝试填充其中一个内圈,但却填充了第 79 个外圈。

换句话说,您正在忘记哪些圈子是哪些圈子。


尝试按以下方式构建代码:

您已经有了一个“iOSCircle”对象,这很好。这个圆形对象还应该包含它的颜色并且能够自行绘制:

@interface Circle : NSObject
@property (nonatomic) CGPoint centre;
@property (nonatomic) CGFloat radius;
@property (nonatomic, strong) UIColor* color;
- (void)draw;
@end

-draw 方法绘制圆,可选地填充颜色(如果已设置):

- (void)draw
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddArc(ctx, self.centre.x, self.centre.y, etc...)
    if (self.color)
    {
        [self.color setFill];
        CGContextDrawPath(ctx, kCGPathFillStroke);
    }
    else
    {
        CGContextStrokePath(ctx);
    }
}

您应该有一个生成圆形对象数组的方法。这将创建 80 个外圈,以及可选的内圈。这还将为每个圆圈分配一种颜色。

你的主要绘制方法就这么简单:

- (void)drawCircle
{
    NSArray* circles = [self generateCircles];
    for (Circle* circle in circles)
    {
        [circle draw];
    }
}

关于ios - 是什么导致 CGContextAddArc 出现这种边缘情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378461/

有关ios - 是什么导致 CGContextAddArc 出现这种边缘情况?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  7. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐