我试图通过子类化它来创建我自己的自定义 UIProgressView,然后覆盖 drawRect 函数。 除了进度填充栏外,一切都按预期工作。我无法获得正确的高度和图像。
图像均采用 Retina 分辨率,模拟器处于 Retina 模式。 图像称为:“progressBar@2x.png”(28px 高)和“progressBarTrack@2x.png”(32px 高)。
自定义进度 View
#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%)。但是进度填充图像绘制不正确。
有人看到我哪里出错了吗?
最佳答案
看起来您正在 -drawRect
中重新分配 self.frame
。
我想你想要这样的东西:
// 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];
}
如何创建自己的进度 View 来覆盖 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
关于objective-c - 自定义 UIProgressView 绘图怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11415887/