0

我正在尝试通过子类化它来创建我自己的自定义 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%)。但是进度填充图像未正确绘制。

有谁看到我哪里出错了?

显示问题的屏幕截图

4

1 回答 1

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
于 2012-07-10T15:17:20.133 回答