Make Background of UIView a Gradient Without Sub Classing

前端 未结 4 1606
庸人自扰
庸人自扰 2020-11-30 21:31

Is there a way to make the background of a UIView a gradient without subclassing it? I\'d rather not use an image file to accomplish this either. It just seems obtuse to hav

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 22:03

    You can use +[UIColor colorWithPatternImage:] to produce a patterned background. Example (bring your own CGGradient):

    // Allocate color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    // Allocate bitmap context
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, 320, 480, 8, 4 * 320, colorSpace, kCGImageAlphaNoneSkipFirst);
    //allocate myGradient
    CGFloat locationList[]  = {0.0f, 1.0f};
    CGFloat colorList[]     = {0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f};
    CGGradientRef myGradient   = CGGradientCreateWithColorComponents(colorSpace, colorList, locationList, 2);
    // Draw Gradient Here
    CGContextDrawLinearGradient(bitmapContext, myGradient, CGPointMake(0.0f, 0.0f), CGPointMake(320.0f, 480.0f), 0);
    // Create a CGImage from context
    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
    // Create a UIImage from CGImage
    UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
    // Release the CGImage
    CGImageRelease(cgImage);
    // Release the bitmap context
    CGContextRelease(bitmapContext);
    // Release the color space
    CGColorSpaceRelease(colorSpace);
    // Create the patterned UIColor and set as background color
    [targetView setBackgroundColor:[UIColor colorWithPatternImage:image]];
    

    It will probably be simpler to just create a UIView subclass though. It will use less memory as well.

提交回复
热议问题