我不止一次遇到UIView(子类)以小数偏移结束的情况,例如:因为它的尺寸是奇数而且它是居中的,或者因为它的位置是基于一个奇数大小的容器的中心。
这会导致文本(或图像)模糊,因为iOS会尝试在半像素偏移上渲染视图(和子视图)。我觉得为每次换帧调用CGRectIntegral()
都不是一个完美的解决方案。
我正在寻找轻松检测这些情况的最佳方法。在写这个问题时,我想出了一个非常激烈的方法,在我当前的项目中发现了比我想象的更多的½。
所以这是为了分享。对于更好或更少激烈的替代品的评论和建议非常受欢迎。
#import <objc/runtime.h>
#import "UIViewOverride.h"
int main(int argc, char *argv[]) {
#ifdef DEBUGVIEW
Method m1,m2;
IMP imp;
m1 = class_getInstanceMethod([UIView class], @selector(setFrame:));
m2 = class_getInstanceMethod([UIViewOverride class], @selector(setFrameOverride:));
imp = method_getImplementation(m2);
class_addMethod([UIView class], @selector(setFrameOverride:), imp, method_getTypeEncoding(m1));
m2 = class_getInstanceMethod([UIView class], @selector(setFrameOverride:));
method_exchangeImplementations(m1,m2);
m1 = class_getInstanceMethod([UIView class], @selector(setCenter:));
m2 = class_getInstanceMethod([UIViewOverride class], @selector(setCenterOverride:));
imp = method_getImplementation(m2);
class_addMethod([UIView class], @selector(setCenterOverride:), imp, method_getTypeEncoding(m1));
m2 = class_getInstanceMethod([UIView class], @selector(setCenterOverride:));
method_exchangeImplementations(m1,m2);
#endif
// etc
这是作为UIView子类实现的,它避免了强制转换和/或编译器警告。
#define FRACTIONAL(f) (fabs(f)-floor(fabs(f))>0.01)
@implementation UIViewOverride
#ifdef DEBUGVIEW
-(void)setFrameOverride:(CGRect)newframe
{
if ( FRACTIONAL(newframe.origin.x) || FRACTIONAL(newframe.origin.y) )
{
[self setBackgroundColor:[UIColor redColor]];
[self setAlpha:0.2];
NSLog(@"fractional offset for %@",self);
}
[self setFrameOverride:newframe]; // not a typo
}
-(void)setCenterOverride:(CGPoint)center
{
[self setCenterOverride:center]; // not a typo
if ( FRACTIONAL(self.frame.origin.x) || FRACTIONAL(self.frame.origin.y) )
{
[self setBackgroundColor:[UIColor greenColor]];
[self setAlpha:0.2];
NSLog(@"fractional via center for %@",self);
}
}
#endif
有问题的视图会生成日志消息并显示透明,红色或绿色。
在调试模式下将 -DDEBUGVIEW
设置为编译器标志。
答案 0 :(得分:8)
您可以通过CoreAnimation仪器及其未对齐标记获得相同的功能。