gpt4 book ai didi

iphone - CGContextShowTextAtPoint在Retina设备上生成非Retina输出

转载 作者:行者123 更新时间:2023-12-01 17:58:01 25 4
gpt4 key购买 nike

我正在尝试向UIImage添加文本,并且正在获取像素化图形。

我尝试了其他一些没有成功的答案:

  • Drawing on the retina display using CoreGraphics - Image pixelated
  • Retina display core graphics font quality
  • Drawing with Core Graphics looks chunky on Retina display

  • 我的代码:
    -(UIImage *)addText:(UIImage *)imgV text:(NSString *)text1
    {
    int w = self.frame.size.width * 2;
    int h = self.frame.size.height * 2;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate
    (NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(context, CGRectMake(0, 0, w, h), imgV.CGImage);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

    char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
    CGContextSelectFont(context, "Arial", 24, kCGEncodingMacRoman);

    // Adjust text;

    CGContextSetTextDrawingMode(context, kCGTextInvisible);
    CGContextShowTextAtPoint(context, 0, 0, text, strlen(text));

    CGPoint pt = CGContextGetTextPosition(context);
    float posx = (w/2 - pt.x)/2.0;
    float posy = 54.0;
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetRGBFillColor(context, 255, 255, 255, 1.0);

    CGContextShowTextAtPoint(context, posx, posy, text, strlen(text));

    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return [UIImage imageWithCGImage:imageMasked];
    }

    最佳答案

    就像彼得所说的那样,使用UIGraphicsBeginImageContextWithOptions。您可能希望将image.scale传递给scale属性(其中image.scale是要绘制的图像之一的比例),或仅使用[UIScreen mainScreen] .scale。

    可以使此代码总体上更简单。尝试类似的方法:

    // Create the image context
    UIGraphicsBeginImageContextWithOptions(_baseImage.size, NO, _baseImage.scale);

    // Draw the image
    CGRect rect = CGRectMake(0, 0, _baseImage.size.width, _baseImage.size.height);
    [_baseImage drawInRect:rect];

    // Get a vertically centered rect for the text drawing
    rect.origin.y = (rect.size.height - FONT_SIZE) / 2 - 2;
    rect = CGRectIntegral(rect);
    rect.size.height = FONT_SIZE;

    // Draw the text
    UIFont *font = [UIFont boldSystemFontOfSize:FONT_SIZE];
    [[UIColor whiteColor] set];
    [text drawInRect:rect withFont:font lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];

    // Get and return the new image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;

    其中 text是NSString对象。

    关于iphone - CGContextShowTextAtPoint在Retina设备上生成非Retina输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128678/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com