iOS模糊文本:一劳永逸地检测和解决它?

mvd*_*vds 5 reflection objective-c uiview swizzling ios

不止一次,我遇到过UIView(子类)以小数偏移结束的情况,例如因为它的尺寸是奇数并且它是居中的,或者因为它的位置是基于奇数大小的容器的中心.

这会导致文本(或图像)模糊,因为iOS会尝试在半像素偏移上渲染视图(和子视图).我觉得要求CGRectIntegral()每一次换帧都不是一个完美的解决方案.

我正在寻找轻松检测这些情况的最佳方法.在写这个问题时,我想出了一个非常激烈的方法,在我当前的项目中揭示了比我想象的更多的½.

所以这是为了分享.对于更好或更少激烈的替代品的评论和建议非常受欢迎.

的main.m

#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
Run Code Online (Sandbox Code Playgroud)

UIViewOverride.m

这是作为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
Run Code Online (Sandbox Code Playgroud)

有问题的视图将生成日志消息并变为透明的红色或绿色.

-DDEBUGVIEW 在调试模式下设置为编译器标志.

Jos*_*erg 8

您可以通过CoreAnimation仪器及其未对齐标记获得相同的功能.