自定义UIProgressView绘图怪异

时间:2012-07-10 14:45:09

标签: objective-c ios drawrect cgrectmake

我试图通过继承它来创建我自己的自定义UIProgressView,然后覆盖drawRect函数。 除了进度填充栏之外,一切都按预期工作。我无法获得正确的高度和图像。

图像均为Retina分辨率,模拟器处于Retina模式。 这些图像被称为:“progressBar@2x.png”(28px高)和“progressBarTrack@2x.png”(32px高)。

CustomProgressView.h

#import <UIKit/UIKit.h>

@interface CustomProgressView : UIProgressView

@end

CustomProgressView.m

#import "CustomProgressView.h"

@implementation CustomProgressView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 16);

    UIImage *progressBarTrack = [[UIImage imageNamed:@"progressBarTrack"] resizableImageWithCapInsets:UIEdgeInsetsZero];
    UIImage *progressBar = [[UIImage imageNamed:@"progressBar"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 5, 4)];

    [progressBarTrack drawInRect:rect];

    NSInteger maximumWidth = rect.size.width - 2;
    NSInteger currentWidth = floor([self progress] * maximumWidth);

    CGRect fillRect = CGRectMake(rect.origin.x + 1, rect.origin.y + 1, currentWidth, 14);

    [progressBar drawInRect:fillRect];
}

@end

生成的ProgressView具有正确的高度和宽度。它也按正确的百分比填写(目前设定为80%)。但是未正确绘制进度填充图像。

有谁看到我哪里出错了?

Screenshot to show the problem

1 个答案:

答案 0 :(得分:2)

您似乎正在self.frame重新分配-drawRect

我想你想要这样的东西:

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGRect bounds = self.bounds ;

    UIImage *progressBarTrack = [ UIImage imageNamed:@"progressBarTrack"] ;
    [ progressBarTrack drawInRect:bounds ] ;

    UIImage *progressBar = [[UIImage imageNamed:@"progressBar"] resizableImageWithCapInsets:(const UIEdgeInsets){ 4.0f, 4.0f, 5.0f, 4.0f } ] ;

    CGRect fillRect = CGRectInset( bounds, 2.0f, 2.0f ) ;
    fillRect.width = floorf( self.progress * maximumWidth );

    [progressBar drawInRect:fillRect];
}

如何创建自己的进度视图覆盖UIView而不是UIProgressView

@interface ProgressView : UIView
@property float progress ;
@end

@implementation ProgressView
@synthesize progress = _progress ;

-(id)initWithFrame:(CGRect)frame
{
    if (( self = [ super initWithFrame:frame ] ))
    {
        self.layer.needsDisplayOnBoundsChange = YES ;
    }

    return self ;
}

-(void)drawRect
{
    // see code above
}

-(void)setProgress:(float)progress
{
    _progress = progress ;
    [ self setNeedsDisplay ] ;
}

@end