2013-02-06 3 views
0

Windows Phone XNA 용으로 개발 중이며 전체 이미지가 필요없는 경우 메모리 영향을 줄이기 위해 더 작은 크기의 텍스처를로드하려고합니다.XNA에서 텍스처 크기 조정을로드하십시오.

public static Texture2D LoadResized(string texturePath, float scale) 
{ 
    Texture2D texLoaded = Content.Load<Texture2D>(texturePath); 
    Vector2 resizedSize = new Vector2(texLoaded.Width * scale, texLoaded.Height * scale); 
    Texture2D resized = ResizeTexture(texLoaded, resizedSize); 
    //texLoaded.Dispose(); 
    return resized; 
} 

public static Texture2D ResizeTexture(Texture2D toResize, Vector2 targetSize) 
{ 
    RenderTarget2D renderTarget = new RenderTarget2D(
     GraphicsDevice, (int)targetSize.X, (int)targetSize.Y); 

    Rectangle destinationRectangle = new Rectangle(
     0, 0, (int)targetSize.X, (int)targetSize.Y); 

    GraphicsDevice.SetRenderTarget(renderTarget); 
    GraphicsDevice.Clear(Color.Transparent); 

    SpriteBatch.Begin(); 
    SpriteBatch.Draw(toResize, destinationRectangle, Color.White); 
    SpriteBatch.End(); 
    GraphicsDevice.SetRenderTarget(null); 

    return renderTarget; 
} 

이 텍스처 크기가 조정됩니다 점에서 작동하지만 메모리 사용에서의 텍스처 "과 같습니다

나의 현재 솔루션은 그리 사용하는 작은 텍스처로 그 렌더 타겟을 반환하는 렌더 타겟을 사용하는 것입니다 texLoaded "는 해제되지 않습니다. 주석 처리되지 않은 Dispose 메서드를 사용하면 SpriteBatch.End()가 삭제 된 예외를 throw합니다.

메모리 사용량을 줄이기 위해 텍스처를로드하는 다른 방법은 있습니까?

답변

0

코드는 입니다. 거의입니다. 거기에 사소한 버그가 있습니다.

주어진 텍스처에 대해 LoadResized이라고하는 시간에만 예외가 발생합니다. ContentManager은로드하는 내용의 내부 캐시를 유지하기 때문에로드하는 모든 내용을 "소유"합니다. 그렇게하면 무언가를 두 번로드하면 캐시 된 객체 만 다시 제공됩니다. Dispose을 호출하면 해당 캐시에 개체가 삭제됩니다.

그러면 해결책은 콘텐츠를로드하는 데 ContentManager을 사용하지 않는 것입니다. 적어도 기본 구현은 아닙니다. 당신은 (코드 this blog post에 기반)과 같이하지 캐시 항목을 수행 ContentManager에서 자신의 클래스를 상속 할 수 있습니다 : Game.Services

class FreshLoadContentManager : ContentManager 
{ 
    public FreshLoadContentManager(IServiceProvider s) : base(s) { } 

    public override T Load<T>(string assetName) 
    { 
     return ReadAsset<T>(assetName, (d) => { }); 
    } 
} 

패스 하나를 만들 수 있습니다. RootDirectory 속성을 설정하는 것을 잊지 마십시오.

그런 다음이 파생 된 콘텐츠 관리자를 사용하여 콘텐츠를로드하십시오. 이제 안전하게로드 할 수 있습니다. Dispose 모든 컨텐츠를 직접로드 할 수 있습니다.

이벤트 핸들러를 RenderTarget2D.ContentLost 이벤트에 연결하여 그래픽 장치가 "손실"되는 경우 크기가 조정 된 텍스처가 다시 ​​만들어 지도록 할 수 있습니다.

관련 문제