【问题标题】:creating UIButton programmatically is blurry than using storyboard以编程方式创建 UIButton 比使用情节提要模糊
【发布时间】:2014-02-27 03:56:26
【问题描述】:

我有两个具有相同图像的自定义 UIButton。一个是以编程方式创建的,它是模糊的,另一个是使用故事板,它工作正常。这是我的代码

    - (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIButton *purchaseButton=[UIButton buttonWithType:UIButtonTypeCustom];
    purchaseButton=[UIButton buttonWithType:UIButtonTypeCustom];
    purchaseButton.frame=CGRectMake(0, 35.5+30, 177, 55);
    [purchaseButton setImage:[UIImage imageNamed:@"GouMai1.png"] forState:UIControlStateNormal];

    [self.view addSubview:purchaseButton];
}

这里是项目下载link(因为GFW,只能上传到中文网站)。这是 Xcode 的错误吗?

【问题讨论】:

    标签: ios objective-c ios7 uibutton


    【解决方案1】:
        purchaseButton.frame=CGRectMake(0, 35.5+30, 177, 55);
    

    你的问题。永远不要给接口对象非整数坐标。会很模糊! - 你会注意到在 Interface Builder(故事板)中你不能这样做。

    原因是屏幕上有物理像素,没有半个像素这样的东西:每个像素都不是开就是关。所以如果你使用半点坐标,它们就不能完全匹配像素,系统会模糊匹配的东西(抗锯齿等)。

    所以,去掉.5,事情会好很多。

    【讨论】:

    • 谢谢。但是在视网膜显示中,1 点=2 像素,那么 0.5 点=1 像素。如何在没有非整数坐标的情况下定位 1 像素?
    • 不要考虑像素。考虑点。您在frame 中的值是积分。仅使用整数值。
    【解决方案2】:

    与@matt 所说的相反,您现在可以执行 0.5,只要它是视网膜设备。你甚至可以有 0.5 的宽度和高度,这就是 iOS 7 在某些地方获得非常细的线条的原因。

    当我运行您的示例应用程序时,在 Retina iPad 模拟器中它并不模糊(也不会比源图像更模糊)。但在非 Retina iPad 模拟器中它是模糊的,这是因为框架中的 .5。

    您需要测试屏幕的比例[UIScreen mainScreen].scale,只有在比例大于 1 时才添加 .5。

    另外请注意,您正在使用该代码创建两个按钮。您可以删除重复的行purchaseButton=[UIButton buttonWithType:UIButtonTypeCustom];

    【讨论】:

    • 非常感谢。我明白了。
    【解决方案3】:
    purchaseButton.frame=CGRectMake(0, 35.5+30, 177, 55);
    

    其实

    • 屏幕会有像素,不会有半个像素
    • 我们为 UI 元素指定的坐标将是点。
    • 点像素比取决于 dpi 和 ppi。

    IOS 主要基于点和 dpi 渲染所有事物,因此尝试使用半点会导致模糊。 (这就是为什么我们不能在界面生成器中将坐标设置为点)

    所以不允许浮动强制它们会导致模糊。请使用最接近的整数值。

    另一方面,由于将偶数除以奇数将主要给出浮点系数。动态计算时必须使用 ceil 和 floor 方法。

    purchaseButton.frame=CGRectMake(0, ceil(self.view.fram.size.width/3), 177, 55);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2012-12-17
      • 2017-10-19
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多