草庐IT

iphone - 频繁重复绘制多个 View 的 CPU 占用最少的方法

coder 2024-01-14 原文

这是一个我离开又回来一段时间的问题。我从来没有真正解决过这个问题。

我一直在尝试使用 CADisplayLink 动态绘制饼图样式进度。当我有 1 - 4 个 uiviews 同时更新时,我的代码工作正常。当我添加更多内容时,馅饼的绘制变得非常生涩。

我想解释一下我一直在尝试的事情,希望有人能指出效率低下的地方并提出更好的绘图方法。

我创建了 16 个 uiview,并为每个添加了一个 CAShapeLayer subview 。这是我要绘制饼图的地方。

我预先计算了代表 0 到 360 度圆的 360 个 CGPath,并将它们存储在一个数组中以尝试提高性能。

在主视图中,我启动一个显示链接,遍历所有其他 View ,计算它应该显示多少完整的饼图,然后找到正确的路径并将其分配给我的形状层。

-(void)makepieslices
{
    pies=[[NSMutableArray alloc]initWithCapacity:360];
    float progress=0;
    for(int i=0;i<=360;i++)

    {
        progress= (i* M_PI)/180;
        CGMutablePathRef thePath = CGPathCreateMutable();
        CGPathMoveToPoint(thePath, NULL, 0.f, 0.f);
        CGPathAddLineToPoint(thePath, NULL, 28, 0.f);
        CGPathAddArc(thePath, NULL, 0.f,0.f, 28, 0.f, progress, NO);
        CGPathCloseSubpath(thePath);
        _pies[i]=thePath;


    }



}

- (void)updatePath:(CADisplayLink *)dLink {

    for (int idx=0; idx<[spinnydelegates count]; idx++) {

        id<SyncSpinUpdateDelegate> delegate = [spinnydelegates objectAtIndex:idx];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [delegate updatePath:dLink];
        });

    }






}

- (void)updatePath:(CADisplayLink *)dLink {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        currentarc=[engineref getsyncpercentForPad:cid pad:pid];

        int progress;

        progress = roundf(currentarc*360);

        dispatch_async(dispatch_get_main_queue(), ^{
            shapeLayer_.path = _pies[progress];

        });



    });


}

当我尝试同时更新超过 4 或 5 个馅饼时,这种技术直接对我不起作用。同时更新 16 个屏幕听起来对我来说对 iPad 来说应该不是什么大问题。所以这让我觉得我做的事情从根本上是错误的。

如果有人能告诉我为什么这种技术会导致屏幕更新抖动,并且如果他们能建议我可以进行调查的不同技术,我将非常感激,这将使我能够顺利地同时执行 16 个 shapelayer 更新。

编辑 只是为了让您了解性能有多糟糕,当我绘制所有 16 个馅饼时,cpu 上升到 20%

*编辑 *

这是基于 studevs 的建议,但我没有看到任何内容。 segmentLayer 是一个 CGLayerRef 作为我的 pieview 的属性。

-(void)makepies
{

    self.layerobjects=[NSMutableArray arrayWithCapacity:360];

    CGFloat progress=0;

    CGContextRef context=UIGraphicsGetCurrentContext();

    for(int i =0;i<360;i++)
    {
        progress= (i*M_PI)/180.0f;

        CGLayerRef segmentlayer=CGLayerCreateWithContext(context, CGSizeMake(30, 30), NULL);
        CGContextRef layerContext=CGLayerGetContext(segmentlayer);
        CGMutablePathRef thePath = CGPathCreateMutable();
        CGPathMoveToPoint(thePath, NULL, 0.f, 0.f);
        CGPathAddLineToPoint(thePath, NULL, 28, 0.f);
        CGPathAddArc(thePath, NULL, 0.f,0.f, 28, 0.f, progress, NO);
        CGPathCloseSubpath(thePath);

        [layerobjects addObject:(id)segmentlayer];
        CGLayerRelease(segmentlayer);
    }

}



-(void)updatePath
{
    int progress;

    currentarc=[engineref getsyncpercent];
    progress = roundf(currentarc*360);


    //shapeLayer_.path = _pies[progress];

    self.pieView.segmentLayer=(CGLayerRef)[layerobjects objectAtIndex:progress];

    [self.pieView setNeedsDisplay];


}

-(void)drawRect:(CGRect)rect
{

    CGContextRef context=UIGraphicsGetCurrentContext();

    CGContextDrawLayerInRect(context, self.bounds, segmentLayer);

}

最佳答案

我认为您应该做的第一件事就是使用 CGPath 在屏幕外缓冲您的段(当前由 CGLayer 对象表示)。对象。来自文档:

Layers are suited for the following:

  • High-quality offscreen rendering of drawing that you plan to reuse. For example, you might be building a scene and plan to reuse the same background. Draw the background scene to a layer and then draw the layer whenever you need it. One added benefit is that you don’t need to know color space or device-dependent information to draw to a layer.

  • Repeated drawing. For example, you might want to create a pattern that consists of the same item drawn over and over. Draw the item to a layer and then repeatedly draw the layer, as shown in Figure 12-1. Any Quartz object that you draw repeatedly—including CGPath, CGShading, and CGPDFPage objects—benefits from improved performance if you draw it to a CGLayer. Note that a layer is not just for onscreen drawing; you can use it for graphics contexts that aren’t screen-oriented, such as a PDF graphics context.

创建一个 UIView绘制饼图的子类。为该馅饼的当前进度为其提供一个实例变量,并覆盖 drawRect:绘制表示该进度的图层。该 View 需要首先获得所需的引用 CGLayer对象,因此使用以下方法实现委托(delegate):

- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context;

然后返回现有的 CGLayerRef 将成为代表的工作,或者如果它尚不存在,请创建它。自 CGLayer只能从 drawRect: 中创建, 此委托(delegate)方法应从 PieView 调用的 drawRect:方法。 PieView应该看起来像这样:

PieView.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>


@class PieView;

@protocol PieViewDelegate <NSObject>

@required
- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context;

@end


@interface PieView : UIView

@property(nonatomic, weak) id <PieViewDelegate> delegate;
@property(nonatomic) NSInteger progress;

@end

PieView.m

#import "PieView.h"


@implementation PieView

@synthesize delegate, progress;

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGLayerRef segmentLayer = [delegate pieView:self segmentLayerForProgress:self.progress context:context];
    CGContextDrawLayerInRect(context, self.bounds, segmentLayer);
}

@end



你的PieView的委托(delegate)(很可能是您的 View Controller )然后实现:

NSString *const SegmentCacheKey = @"SegmentForProgress:";

- (CGLayerRef)pieView:(PieView *)pieView segmentLayerForProgress:(NSInteger)progress context:(CGContextRef)context
{
    // First, try to retrieve the layer from the cache
    NSString *cacheKey = [SegmentCacheKey stringByAppendingFormat:@"%d", progress];
    CGLayerRef segmentLayer = (__bridge_retained CGLayerRef)[segmentsCache objectForKey:cacheKey];

    if (!segmentLayer) {    // If the layer hasn't been created yet
        CGFloat progressAngle = (progress * M_PI) / 180.0f;

        // Create the layer
        segmentLayer = CGLayerCreateWithContext(context, layerSize, NULL);
        CGContextRef layerContext = CGLayerGetContext(segmentLayer);

        // Draw the segment
        CGContextSetFillColorWithColor(layerContext, [[UIColor blueColor] CGColor]);
        CGContextMoveToPoint(layerContext, layerSize.width / 2.0f, layerSize.height / 2.0f);
        CGContextAddArc(layerContext, layerSize.width / 2.0f, layerSize.height / 2.0f, layerSize.width / 2.0f, 0.0f, progressAngle, NO);
        CGContextClosePath(layerContext);
        CGContextFillPath(layerContext);

        // Cache the layer
        [segmentsCache setObject:(__bridge_transfer id)segmentLayer forKey:cacheKey];
    }

    return segmentLayer;
}



所以对于每个馅饼,创建一个新的 PieView并设置它的代表。当你需要更新饼图时,更新 PieViewprogress属性(property)及电话setNeedsDisplay .

我正在使用 NSCache在这里,因为有很多图形被存储,它可能会占用大量内存。您还可以限制绘制的线段数量——100 个可能就足够了。此外,我同意其他评论/答案,您可能会尝试减少更新 View 的频率,因为这会消耗更少的 CPU 和电池电量(可能不需要 60fps)。



我在 iPad(第一代)上对这种方法进行了一些粗略的测试,并设法以 30fps 的速度更新了 50 多个馅饼。

关于iphone - 频繁重复绘制多个 View 的 CPU 占用最少的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8038842/

有关iphone - 频繁重复绘制多个 View 的 CPU 占用最少的方法的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. 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

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  6. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐