Программно изменяющееся изображение рабочего стола
Я пытаюсь изменить изображение на рабочем столе; процедура, которую я придумал, ниже. При первом запуске этого кода изображение с измененным размером отображается на экране в качестве обоев, но в следующий раз реакция не проявляется. Что я делаю неправильно?
-(IBAction)click:(id)sender
{
NSData *sourceData;
NSError *error;
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
screenArray = [NSScreen screens];
screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
screenz = [screenArray objectAtIndex: index];
screenRect = [screenz visibleFrame];
}
NSLog(@"%fx%f",screenRect.size.width, screenRect.size.height);
arrCatDetails = [strCatDetails componentsSeparatedByString:appDelegate.strColDelimiter];
NSString *imageURL = [NSString stringWithFormat:@"upload/product/image/%@_%@_%d.jpg",[arrCatDetails objectAtIndex:0],appDelegate.str104by157Name,iSelectedImgIndex];
NSString *ima = [imageURL lastPathComponent];
NSString *str = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *dataFilePath = [str stringByAppendingPathComponent:ima];
NSString *imagePath = [NSString stringWithFormat:@"file://localhost%@",dataFilePath];
NSURL *url = [[NSURL alloc] init];
url = [NSURL URLWithString:imagePath];
sourceData = [NSData dataWithContentsOfURL:url];
sourceImage = [[NSImage alloc] initWithData: sourceData];
resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(screenRect.size.width, screenRect.size.height)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, screenRect.size.width, screenRect.size.height) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep imageRepWithData:resizedData];
newimage = @"editwall.jpg";
newFilePath = [str stringByAppendingPathComponent:newimage];
NSData* theImageData = [theImageRepresentation representationUsingType:NSJPEGFileType properties:nil];
[theImageData writeToFile: newFilePath atomically: YES];
if([filemgr fileExistsAtPath:newFilePath] == YES)
{
imagePath1 = [NSString stringWithFormat:@"file://localhost%@",newFilePath];
urlz = [NSURL URLWithString:imagePath1];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:nil, NSWorkspaceDesktopImageFillColorKey, [NSNumber numberWithBool:NO], NSWorkspaceDesktopImageAllowClippingKey, [NSNumber numberWithInteger:NSImageScaleProportionallyUpOrDown], NSWorkspaceDesktopImageScalingKey, nil];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:urlz forScreen:[[NSScreen screens] lastObject] options:options error:&error];
}
else
{
NSLog(@"No");
}
[sourceImage release];
[resizedImage release];
}
1 ответ
Почему бы не попробовать -[NSWorkspace setDesktopImageURL:forScreen:options:error:]
? У Apple есть пример проекта DesktopImage, чтобы дать вам представление о том, как его использовать.
Изменить (после более внимательного прочтения кода): возможно, проблема в том, что вы звоните +[NSDictionary dictionaryWithObjectsAndKeys:]
Увидеть nil
в конце списка аргументов? Вот как ты говоришь NSDictionary
что ваш список аргументов готов. Вы не можете положить nil
в списке, потому что это прекратит чтение списка в этой точке. Если вы хотите указать ключ, который не имеет значения, вы должны использовать [NSNull null]
,
Кроме того: у вас есть проблема с управлением памятью в вашем коде:
// allocates memory for an NSURL
NSURL * url = [[NSURL alloc] init];
// allocates more memory for an NSURL, and leaks
// the earlier allocation
url = [NSURL URLWithString:imagePath];
Просто сделайте одно или другое:
// If you do it this way, you will have to call
// [url release] later
NSURL * url = [[NSURL alloc] initWithString:imagePath];
// This memory will be released automatically
NSURL * otherUrl = [NSURL URLWithString:imagePath];