From d83a98f4ce9cfa908f5c54bbd70f03eec07e7553 Mon Sep 17 00:00:00 2001
From: The Android Open Source Project Returns the density scale for this bitmap, expressed as a factor of
- * the default density (160.) For instance, a bitmap designed for
- * displays with a density of 240 will have a density scale of 1.5 whereas a bitmap
- * designed for a density of 160 will have a density scale of 1.0. The default density scale is {@link #DENSITY_SCALE_UNKNOWN}. Specifies the density scale for this bitmap, expressed as a factor of
- * the default density (160.) For instance, a bitmap designed for
- * displays with a density of 240 will have a density scale of 1.5 whereas a bitmap
- * designed for a density of 160 will have a density scale of 1.0.
scale = (bitmap density scale factor) / (target density scale factor)- * - *
Auto scaling is turned off by default. If auto scaling is enabled but the - * bitmap has an unknown density scale, then the bitmap will never be automatically - * scaled at drawing time.
- * - * @return True if the bitmap must be scaled at drawing time, false otherwise. - * - * @see #setAutoScalingEnabled(boolean) - * @see #getDensityScale() - * @see #setDensityScale(float) - * - * @hide pending API council approval - */ - public boolean isAutoScalingEnabled() { - return mAutoScaling; - } - - /** - *Enables or disables auto scaling for this bitmap. When auto scaling is enabled, - * the bitmap will be scaled at drawing time to accomodate the drawing target's pixel - * density. The final scale factor for this bitmap is thus defined:
- * - *scale = (bitmap density scale factor) / (target density scale factor)- * - *
If auto scaling is enabled but the bitmap has an unknown density scale, then - * the bitmap will never be automatically scaled at drawing time.
- * - * @param autoScalingEnabled True to scale the bitmap at drawing time, false otherwise. - * - * @hide pending API council approval - */ - public void setAutoScalingEnabled(boolean autoScalingEnabled) { - mAutoScaling = autoScalingEnabled; - } - - /** - * Sets the nine patch chunk. - * - * @param chunk The definition of the nine patch - * - * @hide - */ - public void setNinePatchChunk(byte[] chunk) { - mNinePatchChunk = chunk; - } - - /** - * Free up the memory associated with this bitmap's pixels, and mark the - * bitmap as "dead", meaning it will throw an exception if getPixels() or - * setPixels() is called, and will draw nothing. This operation cannot be - * reversed, so it should only be called if you are sure there are no - * further uses for the bitmap. This is an advanced call, and normally need - * not be called, since the normal GC process will free up this memory when - * there are no more references to this bitmap. - */ - public void recycle() { - if (!mRecycled) { - nativeRecycle(mNativeBitmap); - mNinePatchChunk = null; - mRecycled = true; - } - } - - /** - * Returns true if this bitmap has been recycled. If so, then it is an error - * to try to access its pixels, and the bitmap will not draw. - * - * @return true if the bitmap has been recycled - */ - public final boolean isRecycled() { - return mRecycled; - } - - /** - * This is called by methods that want to throw an exception if the bitmap - * has already been recycled. - */ - private void checkRecycled(String errorMessage) { - if (mRecycled) { - throw new IllegalStateException(errorMessage); - } - } - - /** - * Common code for checking that x and y are >= 0 - * - * @param x x coordinate to ensure is >= 0 - * @param y y coordinate to ensure is >= 0 - */ - private static void checkXYSign(int x, int y) { - if (x < 0) { - throw new IllegalArgumentException("x must be >= 0"); - } - if (y < 0) { - throw new IllegalArgumentException("y must be >= 0"); - } - } - - /** - * Common code for checking that width and height are > 0 - * - * @param width width to ensure is > 0 - * @param height height to ensure is > 0 - */ - private static void checkWidthHeight(int width, int height) { - if (width <= 0) { - throw new IllegalArgumentException("width must be > 0"); - } - if (height <= 0) { - throw new IllegalArgumentException("height must be > 0"); - } - } - - public enum Config { - // these native values must match up with the enum in SkBitmap.h - ALPHA_8 (2), - RGB_565 (4), - ARGB_4444 (5), - ARGB_8888 (6); - - Config(int ni) { - this.nativeInt = ni; - } - final int nativeInt; - - /* package */ static Config nativeToConfig(int ni) { - return sConfigs[ni]; - } - - private static Config sConfigs[] = { - null, null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888 - }; - } - - /** - * Copy the bitmap's pixels into the specified buffer (allocated by the - * caller). An exception is thrown if the buffer is not large enough to - * hold all of the pixels (taking into account the number of bytes per - * pixel) or if the Buffer subclass is not one of the support types - * (ByteBuffer, ShortBuffer, IntBuffer). - */ - public void copyPixelsToBuffer(Buffer dst) { - int elements = dst.remaining(); - int shift; - if (dst instanceof ByteBuffer) { - shift = 0; - } else if (dst instanceof ShortBuffer) { - shift = 1; - } else if (dst instanceof IntBuffer) { - shift = 2; - } else { - throw new RuntimeException("unsupported Buffer subclass"); - } - - long bufferSize = (long)elements << shift; - long pixelSize = (long)getRowBytes() * getHeight(); - - if (bufferSize < pixelSize) { - throw new RuntimeException("Buffer not large enough for pixels"); - } - - nativeCopyPixelsToBuffer(mNativeBitmap, dst); - - // now update the buffer's position - int position = dst.position(); - position += pixelSize >> shift; - dst.position(position); - } - - /** - * Copy the pixels from the buffer, beginning at the current position, - * overwriting the bitmap's pixels. The data in the buffer is not changed - * in any way (unlike setPixels(), which converts from unpremultipled 32bit - * to whatever the bitmap's native format is. - */ - public void copyPixelsFromBuffer(Buffer src) { - checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); - - int elements = src.remaining(); - int shift; - if (src instanceof ByteBuffer) { - shift = 0; - } else if (src instanceof ShortBuffer) { - shift = 1; - } else if (src instanceof IntBuffer) { - shift = 2; - } else { - throw new RuntimeException("unsupported Buffer subclass"); - } - - long bufferBytes = (long)elements << shift; - long bitmapBytes = (long)getRowBytes() * getHeight(); - - if (bufferBytes < bitmapBytes) { - throw new RuntimeException("Buffer not large enough for pixels"); - } - - nativeCopyPixelsFromBuffer(mNativeBitmap, src); - } - - /** - * Tries to make a new bitmap based on the dimensions of this bitmap, - * setting the new bitmap's config to the one specified, and then copying - * this bitmap's pixels into the new bitmap. If the conversion is not - * supported, or the allocator fails, then this returns NULL. - * - * @param config The desired config for the resulting bitmap - * @param isMutable True if the resulting bitmap should be mutable (i.e. - * its pixels can be modified) - * @return the new bitmap, or null if the copy could not be made. - */ - public Bitmap copy(Config config, boolean isMutable) { - checkRecycled("Can't copy a recycled bitmap"); - return nativeCopy(mNativeBitmap, config.nativeInt, isMutable); - } - - public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, - int dstHeight, boolean filter) { - Matrix m; - synchronized (Bitmap.class) { - // small pool of just 1 matrix - m = sScaleMatrix; - sScaleMatrix = null; - } - - if (m == null) { - m = new Matrix(); - } - - final int width = src.getWidth(); - final int height = src.getHeight(); - final float sx = dstWidth / (float)width; - final float sy = dstHeight / (float)height; - m.setScale(sx, sy); - Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter); - - synchronized (Bitmap.class) { - // do we need to check for null? why not just assign everytime? - if (sScaleMatrix == null) { - sScaleMatrix = m; - } - } - - return b; - } - - /** - * Returns an immutable bitmap from the source bitmap. The new bitmap may - * be the same object as source, or a copy may have been made. - */ - public static Bitmap createBitmap(Bitmap src) { - return createBitmap(src, 0, 0, src.getWidth(), src.getHeight()); - } - - /** - * Returns an immutable bitmap from the specified subset of the source - * bitmap. The new bitmap may be the same object as source, or a copy may - * have been made. - * - * @param source The bitmap we are subsetting - * @param x The x coordinate of the first pixel in source - * @param y The y coordinate of the first pixel in source - * @param width The number of pixels in each row - * @param height The number of rows - */ - public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) { - return createBitmap(source, x, y, width, height, null, false); - } - - /** - * Returns an immutable bitmap from subset of the source bitmap, - * transformed by the optional matrix. - * - * @param source The bitmap we are subsetting - * @param x The x coordinate of the first pixel in source - * @param y The y coordinate of the first pixel in source - * @param width The number of pixels in each row - * @param height The number of rows - * @param m Option matrix to be applied to the pixels - * @param filter true if the source should be filtered. - * Only applies if the matrix contains more than just - * translation. - * @return A bitmap that represents the specified subset of source - * @throws IllegalArgumentException if the x, y, width, height values are - * outside of the dimensions of the source bitmap. - */ - public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, - Matrix m, boolean filter) { - - checkXYSign(x, y); - checkWidthHeight(width, height); - if (x + width > source.getWidth()) { - throw new IllegalArgumentException("x + width must be <= bitmap.width()"); - } - if (y + height > source.getHeight()) { - throw new IllegalArgumentException("y + height must be <= bitmap.height()"); - } - - // check if we can just return our argument unchanged - if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && - height == source.getHeight() && (m == null || m.isIdentity())) { - return source; - } - - int neww = width; - int newh = height; - Canvas canvas = new Canvas(); - Bitmap bitmap; - Paint paint; - - Rect srcR = new Rect(x, y, x + width, y + height); - RectF dstR = new RectF(0, 0, width, height); - - if (m == null || m.isIdentity()) { - bitmap = createBitmap(neww, newh, - source.hasAlpha() ? Config.ARGB_8888 : Config.RGB_565); - paint = null; // not needed - } else { - /* the dst should have alpha if the src does, or if our matrix - doesn't preserve rectness - */ - boolean hasAlpha = source.hasAlpha() || !m.rectStaysRect(); - RectF deviceR = new RectF(); - m.mapRect(deviceR, dstR); - neww = Math.round(deviceR.width()); - newh = Math.round(deviceR.height()); - bitmap = createBitmap(neww, newh, hasAlpha ? Config.ARGB_8888 : Config.RGB_565); - if (hasAlpha) { - bitmap.eraseColor(0); - } - canvas.translate(-deviceR.left, -deviceR.top); - canvas.concat(m); - paint = new Paint(); - paint.setFilterBitmap(filter); - if (!m.rectStaysRect()) { - paint.setAntiAlias(true); - } - } - canvas.setBitmap(bitmap); - canvas.drawBitmap(source, srcR, dstR, paint); - - // The new bitmap was created from a known bitmap source so assume that - // they use the same density scale - bitmap.setDensityScale(source.getDensityScale()); - bitmap.setAutoScalingEnabled(source.isAutoScalingEnabled()); - - return bitmap; - } - - /** - * Returns a mutable bitmap with the specified width and height. - * - * @param width The width of the bitmap - * @param height The height of the bitmap - * @param config The bitmap config to create. - * @throws IllegalArgumentException if the width or height are <= 0 - */ - public static Bitmap createBitmap(int width, int height, Config config) { - Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true); - bm.eraseColor(0); // start with black/transparent pixels - return bm; - } - - /** - * Returns a immutable bitmap with the specified width and height, with each - * pixel value set to the corresponding value in the colors array. - * - * @param colors Array of {@link Color} used to initialize the pixels. - * @param offset Number of values to skip before the first color in the - * array of colors. - * @param stride Number of colors in the array between rows (must be >= - * width or <= -width). - * @param width The width of the bitmap - * @param height The height of the bitmap - * @param config The bitmap config to create. If the config does not - * support per-pixel alpha (e.g. RGB_565), then the alpha - * bytes in the colors[] will be ignored (assumed to be FF) - * @throws IllegalArgumentException if the width or height are <= 0, or if - * the color array's length is less than the number of pixels. - */ - public static Bitmap createBitmap(int colors[], int offset, int stride, - int width, int height, Config config) { - - checkWidthHeight(width, height); - if (Math.abs(stride) < width) { - throw new IllegalArgumentException("abs(stride) must be >= width"); - } - int lastScanline = offset + (height - 1) * stride; - int length = colors.length; - if (offset < 0 || (offset + width > length) || lastScanline < 0 || - (lastScanline + width > length)) { - throw new ArrayIndexOutOfBoundsException(); - } - return nativeCreate(colors, offset, stride, width, height, - config.nativeInt, false); - } - - /** - * Returns a immutable bitmap with the specified width and height, with each - * pixel value set to the corresponding value in the colors array. - * - * @param colors Array of {@link Color} used to initialize the pixels. - * This array must be at least as large as width * height. - * @param width The width of the bitmap - * @param height The height of the bitmap - * @param config The bitmap config to create. If the config does not - * support per-pixel alpha (e.g. RGB_565), then the alpha - * bytes in the colors[] will be ignored (assumed to be FF) - * @throws IllegalArgumentException if the width or height are <= 0, or if - * the color array's length is less than the number of pixels. - */ - public static Bitmap createBitmap(int colors[], int width, int height, Config config) { - return createBitmap(colors, 0, width, width, height, config); - } - - /** - * Returns an optional array of private data, used by the UI system for - * some bitmaps. Not intended to be called by applications. - */ - public byte[] getNinePatchChunk() { - return mNinePatchChunk; - } - - /** - * Specifies the known formats a bitmap can be compressed into - */ - public enum CompressFormat { - JPEG (0), - PNG (1); - - CompressFormat(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * Number of bytes of temp storage we use for communicating between the - * native compressor and the java OutputStream. - */ - private final static int WORKING_COMPRESS_STORAGE = 4096; - - /** - * Write a compressed version of the bitmap to the specified outputstream. - * If this returns true, the bitmap can be reconstructed by passing a - * corresponding inputstream to BitmapFactory.decodeStream(). Note: not - * all Formats support all bitmap configs directly, so it is possible that - * the returned bitmap from BitmapFactory could be in a different bitdepth, - * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque - * pixels). - * - * @param format The format of the compressed image - * @param quality Hint to the compressor, 0-100. 0 meaning compress for - * small size, 100 meaning compress for max quality. Some - * formats, like PNG which is lossless, will ignore the - * quality setting - * @param stream The outputstream to write the compressed data. - * @return true if successfully compressed to the specified stream. - */ - public boolean compress(CompressFormat format, int quality, OutputStream stream) { - checkRecycled("Can't compress a recycled bitmap"); - // do explicit check before calling the native method - if (stream == null) { - throw new NullPointerException(); - } - if (quality < 0 || quality > 100) { - throw new IllegalArgumentException("quality must be 0..100"); - } - return nativeCompress(mNativeBitmap, format.nativeInt, quality, - stream, new byte[WORKING_COMPRESS_STORAGE]); - } - - /** - * Returns true if the bitmap is marked as mutable (i.e. can be drawn into) - */ - public final boolean isMutable() { - return mIsMutable; - } - - /** Returns the bitmap's width */ - public final int getWidth() { - return mWidth == -1 ? mWidth = nativeWidth(mNativeBitmap) : mWidth; - } - - /** Returns the bitmap's height */ - public final int getHeight() { - return mHeight == -1 ? mHeight = nativeHeight(mNativeBitmap) : mHeight; - } - - /** - * Convenience method that returns the width of this bitmap divided - * by the density scale factor. - * - * @return The scaled width of this bitmap, according to the density scale factor. - * - * @hide pending API council approval - */ - public int getScaledWidth() { - final float scale = getDensityScale(); - return scale == DENSITY_SCALE_UNKNOWN ? getWidth() : (int) (getWidth() / scale); - } - - /** - * Convenience method that returns the height of this bitmap divided - * by the density scale factor. - * - * @return The scaled height of this bitmap, according to the density scale factor. - * - * @hide pending API council approval - */ - public int getScaledHeight() { - final float scale = getDensityScale(); - return scale == DENSITY_SCALE_UNKNOWN ? getWidth() : (int) (getHeight() / scale); - } - - /** - * Return the number of bytes between rows in the bitmap's pixels. Note that - * this refers to the pixels as stored natively by the bitmap. If you call - * getPixels() or setPixels(), then the pixels are uniformly treated as - * 32bit values, packed according to the Color class. - * - * @return number of bytes between rows of the native bitmap pixels. - */ - public final int getRowBytes() { - return nativeRowBytes(mNativeBitmap); - } - - /** - * If the bitmap's internal config is in one of the public formats, return - * that config, otherwise return null. - */ - public final Config getConfig() { - return Config.nativeToConfig(nativeConfig(mNativeBitmap)); - } - - /** Returns true if the bitmap's pixels support levels of alpha */ - public final boolean hasAlpha() { - return nativeHasAlpha(mNativeBitmap); - } - - /** - * Fills the bitmap's pixels with the specified {@link Color}. - * - * @throws IllegalStateException if the bitmap is not mutable. - */ - public void eraseColor(int c) { - checkRecycled("Can't erase a recycled bitmap"); - if (!isMutable()) { - throw new IllegalStateException("cannot erase immutable bitmaps"); - } - nativeErase(mNativeBitmap, c); - } - - /** - * Returns the {@link Color} at the specified location. Throws an exception - * if x or y are out of bounds (negative or >= to the width or height - * respectively). - * - * @param x The x coordinate (0...width-1) of the pixel to return - * @param y The y coordinate (0...height-1) of the pixel to return - * @return The argb {@link Color} at the specified coordinate - * @throws IllegalArgumentException if x, y exceed the bitmap's bounds - */ - public int getPixel(int x, int y) { - checkRecycled("Can't call getPixel() on a recycled bitmap"); - checkPixelAccess(x, y); - return nativeGetPixel(mNativeBitmap, x, y); - } - - /** - * Returns in pixels[] a copy of the data in the bitmap. Each value is - * a packed int representing a {@link Color}. The stride parameter allows - * the caller to allow for gaps in the returned pixels array between - * rows. For normal packed results, just pass width for the stride value. - * - * @param pixels The array to receive the bitmap's colors - * @param offset The first index to write into pixels[] - * @param stride The number of entries in pixels[] to skip between - * rows (must be >= bitmap's width). Can be negative. - * @param x The x coordinate of the first pixel to read from - * the bitmap - * @param y The y coordinate of the first pixel to read from - * the bitmap - * @param width The number of pixels to read from each row - * @param height The number of rows to read - * @throws IllegalArgumentException if x, y, width, height exceed the - * bounds of the bitmap, or if abs(stride) < width. - * @throws ArrayIndexOutOfBoundsException if the pixels array is too small - * to receive the specified number of pixels. - */ - public void getPixels(int[] pixels, int offset, int stride, - int x, int y, int width, int height) { - checkRecycled("Can't call getPixels() on a recycled bitmap"); - if (width == 0 || height == 0) { - return; // nothing to do - } - checkPixelsAccess(x, y, width, height, offset, stride, pixels); - nativeGetPixels(mNativeBitmap, pixels, offset, stride, - x, y, width, height); - } - - /** - * Shared code to check for illegal arguments passed to getPixel() - * or setPixel() - * @param x x coordinate of the pixel - * @param y y coordinate of the pixel - */ - private void checkPixelAccess(int x, int y) { - checkXYSign(x, y); - if (x >= getWidth()) { - throw new IllegalArgumentException("x must be < bitmap.width()"); - } - if (y >= getHeight()) { - throw new IllegalArgumentException("y must be < bitmap.height()"); - } - } - - /** - * Shared code to check for illegal arguments passed to getPixels() - * or setPixels() - * - * @param x left edge of the area of pixels to access - * @param y top edge of the area of pixels to access - * @param width width of the area of pixels to access - * @param height height of the area of pixels to access - * @param offset offset into pixels[] array - * @param stride number of elements in pixels[] between each logical row - * @param pixels array to hold the area of pixels being accessed - */ - private void checkPixelsAccess(int x, int y, int width, int height, - int offset, int stride, int pixels[]) { - checkXYSign(x, y); - if (width < 0) { - throw new IllegalArgumentException("width must be >= 0"); - } - if (height < 0) { - throw new IllegalArgumentException("height must be >= 0"); - } - if (x + width > getWidth()) { - throw new IllegalArgumentException( - "x + width must be <= bitmap.width()"); - } - if (y + height > getHeight()) { - throw new IllegalArgumentException( - "y + height must be <= bitmap.height()"); - } - if (Math.abs(stride) < width) { - throw new IllegalArgumentException("abs(stride) must be >= width"); - } - int lastScanline = offset + (height - 1) * stride; - int length = pixels.length; - if (offset < 0 || (offset + width > length) - || lastScanline < 0 - || (lastScanline + width > length)) { - throw new ArrayIndexOutOfBoundsException(); - } - } - - /** - * Write the specified {@link Color} into the bitmap (assuming it is - * mutable) at the x,y coordinate. - * - * @param x The x coordinate of the pixel to replace (0...width-1) - * @param y The y coordinate of the pixel to replace (0...height-1) - * @param color The {@link Color} to write into the bitmap - * @throws IllegalStateException if the bitmap is not mutable - * @throws IllegalArgumentException if x, y are outside of the bitmap's - * bounds. - */ - public void setPixel(int x, int y, int color) { - checkRecycled("Can't call setPixel() on a recycled bitmap"); - if (!isMutable()) { - throw new IllegalStateException(); - } - checkPixelAccess(x, y); - nativeSetPixel(mNativeBitmap, x, y, color); - } - - /** - * Replace pixels in the bitmap with the colors in the array. Each element - * in the array is a packed int prepresenting a {@link Color} - * - * @param pixels The colors to write to the bitmap - * @param offset The index of the first color to read from pixels[] - * @param stride The number of colors in pixels[] to skip between rows. - * Normally this value will be the same as the width of - * the bitmap, but it can be larger (or negative). - * @param x The x coordinate of the first pixel to write to in - * the bitmap. - * @param y The y coordinate of the first pixel to write to in - * the bitmap. - * @param width The number of colors to copy from pixels[] per row - * @param height The number of rows to write to the bitmap - * @throws IllegalStateException if the bitmap is not mutable - * @throws IllegalArgumentException if x, y, width, height are outside of - * the bitmap's bounds. - * @throws ArrayIndexOutOfBoundsException if the pixels array is too small - * to receive the specified number of pixels. - */ - public void setPixels(int[] pixels, int offset, int stride, - int x, int y, int width, int height) { - checkRecycled("Can't call setPixels() on a recycled bitmap"); - if (!isMutable()) { - throw new IllegalStateException(); - } - if (width == 0 || height == 0) { - return; // nothing to do - } - checkPixelsAccess(x, y, width, height, offset, stride, pixels); - nativeSetPixels(mNativeBitmap, pixels, offset, stride, - x, y, width, height); - } - - public static final Parcelable.CreatorReturns the density scale for this Canvas' backing bitmap, expressed as a - * factor of the default density (160dpi.) For instance, a bitmap designed for - * 240dpi displays will have a density scale of 1.5 whereas a bitmap - * designed for 160dpi will have a density scale of 1.0.
- * - *The default density scale is {@link Bitmap#DENSITY_SCALE_UNKNOWN}.
- * - * @return A scaling factor of the default density (160dpi) or - * {@link Bitmap#DENSITY_SCALE_UNKNOWN} if the scaling factor is unknown. - * - * @see #setDensityScale(float) - * @see Bitmap#getDensityScale() - * - * @hide pending API council approval - */ - public float getDensityScale() { - if (mBitmap != null) { - return mBitmap.getDensityScale(); - } - return mDensityScale; - } - - /** - *Specifies the density scale for this Canvas' backing bitmap, expressed as a - * factor of the default density (160dpi.) For instance, a bitmap designed for - * 240dpi displays will have a density scale of 1.5 whereas a bitmap - * designed for 160dpi will have a density scale of 1.0.
- * - * @param densityScale The density scaling factor to use with this bitmap or - * {@link Bitmap#DENSITY_SCALE_UNKNOWN} if the factor is unknown. - * - * @see #getDensityScale() - * @see Bitmap#setDensityScale(float) - * - * @hide pending API council approval - */ - public void setDensityScale(float densityScale) { - if (mBitmap != null) { - mBitmap.setDensityScale(densityScale); - } - mDensityScale = densityScale; - if (mDensityScale == Bitmap.DENSITY_SCALE_UNKNOWN) mDensityScale = 1.0f; - } - - // the SAVE_FLAG constants must match their native equivalents - - /** restore the current matrix when restore() is called */ - public static final int MATRIX_SAVE_FLAG = 0x01; - /** restore the current clip when restore() is called */ - public static final int CLIP_SAVE_FLAG = 0x02; - /** the layer needs to per-pixel alpha */ - public static final int HAS_ALPHA_LAYER_SAVE_FLAG = 0x04; - /** the layer needs to 8-bits per color component */ - public static final int FULL_COLOR_LAYER_SAVE_FLAG = 0x08; - /** clip against the layer's bounds */ - public static final int CLIP_TO_LAYER_SAVE_FLAG = 0x10; - /** restore everything when restore() is called */ - public static final int ALL_SAVE_FLAG = 0x1F; - - /** - * Saves the current matrix and clip onto a private stack. Subsequent - * calls to translate,scale,rotate,skew,concat or clipRect,clipPath - * will all operate as usual, but when the balancing call to restore() - * is made, those calls will be forgotten, and the settings that existed - * before the save() will be reinstated. - * - * @return The value to pass to restoreToCount() to balance this save() - */ - public native int save(); - - /** - * Based on saveFlags, can save the current matrix and clip onto a private - * stack. Subsequent calls to translate,scale,rotate,skew,concat or - * clipRect,clipPath will all operate as usual, but when the balancing - * call to restore() is made, those calls will be forgotten, and the - * settings that existed before the save() will be reinstated. - * - * @param saveFlags flag bits that specify which parts of the Canvas state - * to save/restore - * @return The value to pass to restoreToCount() to balance this save() - */ - public native int save(int saveFlags); - - /** - * This behaves the same as save(), but in addition it allocates an - * offscreen bitmap. All drawing calls are directed there, and only when - * the balancing call to restore() is made is that offscreen transfered to - * the canvas (or the previous layer). Subsequent calls to translate, - * scale, rotate, skew, concat or clipRect, clipPath all operate on this - * copy. When the balancing call to restore() is made, this copy is - * deleted and the previous matrix/clip state is restored. - * - * @param bounds May be null. The maximum size the offscreen bitmap - * needs to be (in local coordinates) - * @param paint This is copied, and is applied to the offscreen when - * restore() is called. - * @param saveFlags see _SAVE_FLAG constants - * @return value to pass to restoreToCount() to balance this save() - */ - public int saveLayer(RectF bounds, Paint paint, int saveFlags) { - return native_saveLayer(mNativeCanvas, bounds, - paint != null ? paint.mNativePaint : 0, - saveFlags); - } - - /** - * Helper version of saveLayer() that takes 4 values rather than a RectF. - */ - public int saveLayer(float left, float top, float right, float bottom, - Paint paint, int saveFlags) { - return native_saveLayer(mNativeCanvas, left, top, right, bottom, - paint != null ? paint.mNativePaint : 0, - saveFlags); - } - - /** - * This behaves the same as save(), but in addition it allocates an - * offscreen bitmap. All drawing calls are directed there, and only when - * the balancing call to restore() is made is that offscreen transfered to - * the canvas (or the previous layer). Subsequent calls to translate, - * scale, rotate, skew, concat or clipRect, clipPath all operate on this - * copy. When the balancing call to restore() is made, this copy is - * deleted and the previous matrix/clip state is restored. - * - * @param bounds The maximum size the offscreen bitmap needs to be - * (in local coordinates) - * @param alpha The alpha to apply to the offscreen when when it is - drawn during restore() - * @param saveFlags see _SAVE_FLAG constants - * @return value to pass to restoreToCount() to balance this call - */ - public int saveLayerAlpha(RectF bounds, int alpha, int saveFlags) { - alpha = Math.min(255, Math.max(0, alpha)); - return native_saveLayerAlpha(mNativeCanvas, bounds, alpha, saveFlags); - } - - /** - * Helper for saveLayerAlpha() that takes 4 values instead of a RectF. - */ - public int saveLayerAlpha(float left, float top, float right, float bottom, - int alpha, int saveFlags) { - return native_saveLayerAlpha(mNativeCanvas, left, top, right, bottom, - alpha, saveFlags); - } - - /** - * This call balances a previous call to save(), and is used to remove all - * modifications to the matrix/clip state since the last save call. It is - * an error to call restore() more times than save() was called. - */ - public native void restore(); - - /** - * Returns the number of matrix/clip states on the Canvas' private stack. - * This will equal # save() calls - # restore() calls. - */ - public native int getSaveCount(); - - /** - * Efficient way to pop any calls to save() that happened after the save - * count reached saveCount. It is an error for saveCount to be less than 1. - * - * Example: - * int count = canvas.save(); - * ... // more calls potentially to save() - * canvas.restoreToCount(count); - * // now the canvas is back in the same state it was before the initial - * // call to save(). - * - * @param saveCount The save level to restore to. - */ - public native void restoreToCount(int saveCount); - - /** - * Preconcat the current matrix with the specified translation - * - * @param dx The distance to translate in X - * @param dy The distance to translate in Y - */ - public native void translate(float dx, float dy); - - /** - * Preconcat the current matrix with the specified scale. - * - * @param sx The amount to scale in X - * @param sy The amount to scale in Y - */ - public native void scale(float sx, float sy); - - /** - * Preconcat the current matrix with the specified scale. - * - * @param sx The amount to scale in X - * @param sy The amount to scale in Y - * @param px The x-coord for the pivot point (unchanged by the rotation) - * @param py The y-coord for the pivot point (unchanged by the rotation) - */ - public final void scale(float sx, float sy, float px, float py) { - translate(px, py); - scale(sx, sy); - translate(-px, -py); - } - - /** - * Preconcat the current matrix with the specified rotation. - * - * @param degrees The amount to rotate, in degrees - */ - public native void rotate(float degrees); - - /** - * Preconcat the current matrix with the specified rotation. - * - * @param degrees The amount to rotate, in degrees - * @param px The x-coord for the pivot point (unchanged by the rotation) - * @param py The y-coord for the pivot point (unchanged by the rotation) - */ - public final void rotate(float degrees, float px, float py) { - translate(px, py); - rotate(degrees); - translate(-px, -py); - } - - /** - * Preconcat the current matrix with the specified skew. - * - * @param sx The amount to skew in X - * @param sy The amount to skew in Y - */ - public native void skew(float sx, float sy); - - /** - * Preconcat the current matrix with the specified matrix. - * - * @param matrix The matrix to preconcatenate with the current matrix - */ - public void concat(Matrix matrix) { - native_concat(mNativeCanvas, matrix.native_instance); - } - - /** - * Completely replace the current matrix with the specified matrix. If the - * matrix parameter is null, then the current matrix is reset to identity. - * - * @param matrix The matrix to replace the current matrix with. If it is - * null, set the current matrix to identity. - */ - public void setMatrix(Matrix matrix) { - native_setMatrix(mNativeCanvas, - matrix == null ? 0 : matrix.native_instance); - } - - /** - * Return, in ctm, the current transformation matrix. This does not alter - * the matrix in the canvas, but just returns a copy of it. - */ - public void getMatrix(Matrix ctm) { - native_getCTM(mNativeCanvas, ctm.native_instance); - } - - /** - * Return a new matrix with a copy of the canvas' current transformation - * matrix. - */ - public final Matrix getMatrix() { - Matrix m = new Matrix(); - getMatrix(m); - return m; - } - - /** - * Modify the current clip with the specified rectangle. - * - * @param rect The rect to intersect with the current clip - * @param op How the clip is modified - * @return true if the resulting clip is non-empty - */ - public boolean clipRect(RectF rect, Region.Op op) { - return native_clipRect(mNativeCanvas, - rect.left, rect.top, rect.right, rect.bottom, - op.nativeInt); - } - - /** - * Modify the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param rect The rectangle to intersect with the current clip. - * @param op How the clip is modified - * @return true if the resulting clip is non-empty - */ - public boolean clipRect(Rect rect, Region.Op op) { - return native_clipRect(mNativeCanvas, - rect.left, rect.top, rect.right, rect.bottom, - op.nativeInt); - } - - /** - * Intersect the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param rect The rectangle to intersect with the current clip. - * @return true if the resulting clip is non-empty - */ - public native boolean clipRect(RectF rect); - - /** - * Intersect the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param rect The rectangle to intersect with the current clip. - * @return true if the resulting clip is non-empty - */ - public native boolean clipRect(Rect rect); - - /** - * Modify the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param left The left side of the rectangle to intersect with the - * current clip - * @param top The top of the rectangle to intersect with the current - * clip - * @param right The right side of the rectangle to intersect with the - * current clip - * @param bottom The bottom of the rectangle to intersect with the current - * clip - * @param op How the clip is modified - * @return true if the resulting clip is non-empty - */ - public boolean clipRect(float left, float top, float right, float bottom, - Region.Op op) { - return native_clipRect(mNativeCanvas, left, top, right, bottom, - op.nativeInt); - } - - /** - * Intersect the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param left The left side of the rectangle to intersect with the - * current clip - * @param top The top of the rectangle to intersect with the current clip - * @param right The right side of the rectangle to intersect with the - * current clip - * @param bottom The bottom of the rectangle to intersect with the current - * clip - * @return true if the resulting clip is non-empty - */ - public native boolean clipRect(float left, float top, - float right, float bottom); - - /** - * Intersect the current clip with the specified rectangle, which is - * expressed in local coordinates. - * - * @param left The left side of the rectangle to intersect with the - * current clip - * @param top The top of the rectangle to intersect with the current clip - * @param right The right side of the rectangle to intersect with the - * current clip - * @param bottom The bottom of the rectangle to intersect with the current - * clip - * @return true if the resulting clip is non-empty - */ - public native boolean clipRect(int left, int top, - int right, int bottom); - - /** - * Modify the current clip with the specified path. - * - * @param path The path to operate on the current clip - * @param op How the clip is modified - * @return true if the resulting is non-empty - */ - public boolean clipPath(Path path, Region.Op op) { - return native_clipPath(mNativeCanvas, path.ni(), op.nativeInt); - } - - /** - * Intersect the current clip with the specified path. - * - * @param path The path to intersect with the current clip - * @return true if the resulting is non-empty - */ - public boolean clipPath(Path path) { - return clipPath(path, Region.Op.INTERSECT); - } - - /** - * Modify the current clip with the specified region. Note that unlike - * clipRect() and clipPath() which transform their arguments by the - * current matrix, clipRegion() assumes its argument is already in the - * coordinate system of the current layer's bitmap, and so not - * transformation is performed. - * - * @param region The region to operate on the current clip, based on op - * @param op How the clip is modified - * @return true if the resulting is non-empty - */ - public boolean clipRegion(Region region, Region.Op op) { - return native_clipRegion(mNativeCanvas, region.ni(), op.nativeInt); - } - - /** - * Intersect the current clip with the specified region. Note that unlike - * clipRect() and clipPath() which transform their arguments by the - * current matrix, clipRegion() assumes its argument is already in the - * coordinate system of the current layer's bitmap, and so not - * transformation is performed. - * - * @param region The region to operate on the current clip, based on op - * @return true if the resulting is non-empty - */ - public boolean clipRegion(Region region) { - return clipRegion(region, Region.Op.INTERSECT); - } - - public DrawFilter getDrawFilter() { - return mDrawFilter; - } - - public void setDrawFilter(DrawFilter filter) { - int nativeFilter = 0; - if (filter != null) { - nativeFilter = filter.mNativeInt; - } - mDrawFilter = filter; - nativeSetDrawFilter(mNativeCanvas, nativeFilter); - } - - public enum EdgeType { - BW(0), //!< treat edges by just rounding to nearest pixel boundary - AA(1); //!< treat edges by rounding-out, since they may be antialiased - - EdgeType(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * Return true if the specified rectangle, after being transformed by the - * current matrix, would lie completely outside of the current clip. Call - * this to check if an area you intend to draw into is clipped out (and - * therefore you can skip making the draw calls). - * - * @param rect the rect to compare with the current clip - * @param type specifies how to treat the edges (BW or antialiased) - * @return true if the rect (transformed by the canvas' matrix) - * does not intersect with the canvas' clip - */ - public boolean quickReject(RectF rect, EdgeType type) { - return native_quickReject(mNativeCanvas, rect, type.nativeInt); - } - - /** - * Return true if the specified path, after being transformed by the - * current matrix, would lie completely outside of the current clip. Call - * this to check if an area you intend to draw into is clipped out (and - * therefore you can skip making the draw calls). Note: for speed it may - * return false even if the path itself might not intersect the clip - * (i.e. the bounds of the path intersects, but the path does not). - * - * @param path The path to compare with the current clip - * @param type true if the path should be considered antialiased, - * since that means it may - * affect a larger area (more pixels) than - * non-antialiased. - * @return true if the path (transformed by the canvas' matrix) - * does not intersect with the canvas' clip - */ - public boolean quickReject(Path path, EdgeType type) { - return native_quickReject(mNativeCanvas, path.ni(), type.nativeInt); - } - - /** - * Return true if the specified rectangle, after being transformed by the - * current matrix, would lie completely outside of the current clip. Call - * this to check if an area you intend to draw into is clipped out (and - * therefore you can skip making the draw calls). - * - * @param left The left side of the rectangle to compare with the - * current clip - * @param top The top of the rectangle to compare with the current - * clip - * @param right The right side of the rectangle to compare with the - * current clip - * @param bottom The bottom of the rectangle to compare with the - * current clip - * @param type true if the rect should be considered antialiased, - * since that means it may affect a larger area (more - * pixels) than non-antialiased. - * @return true if the rect (transformed by the canvas' matrix) - * does not intersect with the canvas' clip - */ - public boolean quickReject(float left, float top, float right, float bottom, - EdgeType type) { - return native_quickReject(mNativeCanvas, left, top, right, bottom, - type.nativeInt); - } - - /** - * Retrieve the clip bounds, returning true if they are non-empty. - * - * @param bounds Return the clip bounds here. If it is null, ignore it but - * still return true if the current clip is non-empty. - * @return true if the current clip is non-empty. - */ - public boolean getClipBounds(Rect bounds) { - return native_getClipBounds(mNativeCanvas, bounds); - } - - /** - * Retrieve the clip bounds. - * - * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty. - */ - public final Rect getClipBounds() { - Rect r = new Rect(); - getClipBounds(r); - return r; - } - - /** - * Fill the entire canvas' bitmap (restricted to the current clip) with the - * specified RGB color, using srcover porterduff mode. - * - * @param r red component (0..255) of the color to draw onto the canvas - * @param g green component (0..255) of the color to draw onto the canvas - * @param b blue component (0..255) of the color to draw onto the canvas - */ - public void drawRGB(int r, int g, int b) { - native_drawRGB(mNativeCanvas, r, g, b); - } - - /** - * Fill the entire canvas' bitmap (restricted to the current clip) with the - * specified ARGB color, using srcover porterduff mode. - * - * @param a alpha component (0..255) of the color to draw onto the canvas - * @param r red component (0..255) of the color to draw onto the canvas - * @param g green component (0..255) of the color to draw onto the canvas - * @param b blue component (0..255) of the color to draw onto the canvas - */ - public void drawARGB(int a, int r, int g, int b) { - native_drawARGB(mNativeCanvas, a, r, g, b); - } - - /** - * Fill the entire canvas' bitmap (restricted to the current clip) with the - * specified color, using srcover porterduff mode. - * - * @param color the color to draw onto the canvas - */ - public void drawColor(int color) { - native_drawColor(mNativeCanvas, color); - } - - /** - * Fill the entire canvas' bitmap (restricted to the current clip) with the - * specified color and porter-duff xfermode. - * - * @param color the color to draw with - * @param mode the porter-duff mode to apply to the color - */ - public void drawColor(int color, PorterDuff.Mode mode) { - native_drawColor(mNativeCanvas, color, mode.nativeInt); - } - - /** - * Fill the entire canvas' bitmap (restricted to the current clip) with - * the specified paint. This is equivalent (but faster) to drawing an - * infinitely large rectangle with the specified paint. - * - * @param paint The paint used to draw onto the canvas - */ - public void drawPaint(Paint paint) { - native_drawPaint(mNativeCanvas, paint.mNativePaint); - } - - /** - * Draw a series of points. Each point is centered at the coordinate - * specified by pts[], and its diameter is specified by the paint's stroke - * width (as transformed by the canvas' CTM), with special treatment for - * a stroke width of 0, which always draws exactly 1 pixel (or at most 4 - * if antialiasing is enabled). The shape of the point is controlled by - * the paint's Cap type. The shape is a square, unless the cap type is - * Round, in which case the shape is a circle. - * - * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] - * @param offset Number of values to skip before starting to draw. - * @param count The number of values to process, after skipping offset - * of them. Since one point uses two values, the number of - * "points" that are drawn is really (count >> 1). - * @param paint The paint used to draw the points - */ - public native void drawPoints(float[] pts, int offset, int count, - Paint paint); - - /** - * Helper for drawPoints() that assumes you want to draw the entire array - */ - public void drawPoints(float[] pts, Paint paint) { - drawPoints(pts, 0, pts.length, paint); - } - - /** - * Helper for drawPoints() for drawing a single point. - */ - public native void drawPoint(float x, float y, Paint paint); - - /** - * Draw a line segment with the specified start and stop x,y coordinates, - * using the specified paint. NOTE: since a line is always "framed", the - * Style is ignored in the paint. - * - * @param startX The x-coordinate of the start point of the line - * @param startY The y-coordinate of the start point of the line - * @param paint The paint used to draw the line - */ - public void drawLine(float startX, float startY, float stopX, float stopY, - Paint paint) { - native_drawLine(mNativeCanvas, startX, startY, stopX, stopY, - paint.mNativePaint); - } - - /** - * Draw a series of lines. Each line is taken from 4 consecutive values - * in the pts array. Thus to draw 1 line, the array must contain at least 4 - * values. This is logically the same as drawing the array as follows: - * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by - * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on. - * - * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] - * @param offset Number of values in the array to skip before drawing. - * @param count The number of values in the array to process, after - * skipping "offset" of them. Since each line uses 4 values, - * the number of "lines" that are drawn is really - * (count >> 2). - * @param paint The paint used to draw the points - */ - public native void drawLines(float[] pts, int offset, int count, - Paint paint); - - public void drawLines(float[] pts, Paint paint) { - drawLines(pts, 0, pts.length, paint); - } - - /** - * Draw the specified Rect using the specified paint. The rectangle will - * be filled or framed based on the Style in the paint. - * - * @param rect The rect to be drawn - * @param paint The paint used to draw the rect - */ - public void drawRect(RectF rect, Paint paint) { - native_drawRect(mNativeCanvas, rect, paint.mNativePaint); - } - - /** - * Draw the specified Rect using the specified Paint. The rectangle - * will be filled or framed based on the Style in the paint. - * - * @param r The rectangle to be drawn. - * @param paint The paint used to draw the rectangle - */ - public void drawRect(Rect r, Paint paint) { - drawRect(r.left, r.top, r.right, r.bottom, paint); - } - - - /** - * Draw the specified Rect using the specified paint. The rectangle will - * be filled or framed based on the Style in the paint. - * - * @param left The left side of the rectangle to be drawn - * @param top The top side of the rectangle to be drawn - * @param right The right side of the rectangle to be drawn - * @param bottom The bottom side of the rectangle to be drawn - * @param paint The paint used to draw the rect - */ - public void drawRect(float left, float top, float right, float bottom, - Paint paint) { - native_drawRect(mNativeCanvas, left, top, right, bottom, - paint.mNativePaint); - } - - /** - * Draw the specified oval using the specified paint. The oval will be - * filled or framed based on the Style in the paint. - * - * @param oval The rectangle bounds of the oval to be drawn - */ - public void drawOval(RectF oval, Paint paint) { - if (oval == null) { - throw new NullPointerException(); - } - native_drawOval(mNativeCanvas, oval, paint.mNativePaint); - } - - /** - * Draw the specified circle using the specified paint. If radius is <= 0, - * then nothing will be drawn. The circle will be filled or framed based - * on the Style in the paint. - * - * @param cx The x-coordinate of the center of the cirle to be drawn - * @param cy The y-coordinate of the center of the cirle to be drawn - * @param radius The radius of the cirle to be drawn - * @param paint The paint used to draw the circle - */ - public void drawCircle(float cx, float cy, float radius, Paint paint) { - native_drawCircle(mNativeCanvas, cx, cy, radius, - paint.mNativePaint); - } - - /** - * Draw the specified arc, which will be scaled to fit inside the - * specified oval. If the sweep angle is >= 360, then the oval is drawn - * completely. Note that this differs slightly from SkPath::arcTo, which - * treats the sweep angle mod 360. - * - * @param oval The bounds of oval used to define the shape and size - * of the arc - * @param startAngle Starting angle (in degrees) where the arc begins - * @param sweepAngle Sweep angle (in degrees) measured clockwise - * @param useCenter If true, include the center of the oval in the arc, and - close it if it is being stroked. This will draw a wedge - * @param paint The paint used to draw the arc - */ - public void drawArc(RectF oval, float startAngle, float sweepAngle, - boolean useCenter, Paint paint) { - if (oval == null) { - throw new NullPointerException(); - } - native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle, - useCenter, paint.mNativePaint); - } - - /** - * Draw the specified round-rect using the specified paint. The roundrect - * will be filled or framed based on the Style in the paint. - * - * @param rect The rectangular bounds of the roundRect to be drawn - * @param rx The x-radius of the oval used to round the corners - * @param ry The y-radius of the oval used to round the corners - * @param paint The paint used to draw the roundRect - */ - public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) { - if (rect == null) { - throw new NullPointerException(); - } - native_drawRoundRect(mNativeCanvas, rect, rx, ry, - paint.mNativePaint); - } - - /** - * Draw the specified path using the specified paint. The path will be - * filled or framed based on the Style in the paint. - * - * @param path The path to be drawn - * @param paint The paint used to draw the path - */ - public void drawPath(Path path, Paint paint) { - native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint); - } - - private static void throwIfRecycled(Bitmap bitmap) { - if (bitmap.isRecycled()) { - throw new RuntimeException( - "Canvas: trying to use a recycled bitmap " + bitmap); - } - } - - /** - * Draw the specified bitmap, with its top/left corner at (x,y), using - * the specified paint, transformed by the current matrix. - * Note: if the paint contains a maskfilter that generates a mask which - * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), - * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. - * Thus the color outside of the original width/height will be the edge - * color replicated. - * - * @param bitmap The bitmap to be drawn - * @param left The position of the left side of the bitmap being drawn - * @param top The position of the top side of the bitmap being drawn - * @param paint The paint used to draw the bitmap (may be null) - */ - public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) { - throwIfRecycled(bitmap); - native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top, - paint != null ? paint.mNativePaint : 0, bitmap.isAutoScalingEnabled(), - bitmap.getDensityScale()); - } - - /** - * Draw the specified bitmap, scaling/translating automatically to fill - * the destination rectangle. If the source rectangle is not null, it - * specifies the subset of the bitmap to draw. - * Note: if the paint contains a maskfilter that generates a mask which - * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), - * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. - * Thus the color outside of the original width/height will be the edge - * color replicated. - * - * @param bitmap The bitmap to be drawn - * @param src May be null. The subset of the bitmap to be drawn - * @param dst The rectangle that the bitmap will be scaled/translated - * to fit into - * @param paint May be null. The paint used to draw the bitmap - */ - public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) { - if (dst == null) { - throw new NullPointerException(); - } - throwIfRecycled(bitmap); - native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst, - paint != null ? paint.mNativePaint : 0); - } - - /** - * Draw the specified bitmap, scaling/translating automatically to fill - * the destination rectangle. If the source rectangle is not null, it - * specifies the subset of the bitmap to draw. - * Note: if the paint contains a maskfilter that generates a mask which - * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), - * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. - * Thus the color outside of the original width/height will be the edge - * color replicated. - * - * @param bitmap The bitmap to be drawn - * @param src May be null. The subset of the bitmap to be drawn - * @param dst The rectangle that the bitmap will be scaled/translated - * to fit into - * @param paint May be null. The paint used to draw the bitmap - */ - public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) { - if (dst == null) { - throw new NullPointerException(); - } - throwIfRecycled(bitmap); - native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst, - paint != null ? paint.mNativePaint : 0); - } - - /** - * Treat the specified array of colors as a bitmap, and draw it. This gives - * the same result as first creating a bitmap from the array, and then - * drawing it, but this method avoids explicitly creating a bitmap object - * which can be more efficient if the colors are changing often. - * - * @param colors Array of colors representing the pixels of the bitmap - * @param offset Offset into the array of colors for the first pixel - * @param stride The number of of colors in the array between rows (must be - * >= width or <= -width). - * @param x The X coordinate for where to draw the bitmap - * @param y The Y coordinate for where to draw the bitmap - * @param width The width of the bitmap - * @param height The height of the bitmap - * @param hasAlpha True if the alpha channel of the colors contains valid - * values. If false, the alpha byte is ignored (assumed to - * be 0xFF for every pixel). - * @param paint May be null. The paint used to draw the bitmap - */ - public void drawBitmap(int[] colors, int offset, int stride, float x, - float y, int width, int height, boolean hasAlpha, - Paint paint) { - // check for valid input - if (width < 0) { - throw new IllegalArgumentException("width must be >= 0"); - } - if (height < 0) { - throw new IllegalArgumentException("height must be >= 0"); - } - if (Math.abs(stride) < width) { - throw new IllegalArgumentException("abs(stride) must be >= width"); - } - int lastScanline = offset + (height - 1) * stride; - int length = colors.length; - if (offset < 0 || (offset + width > length) || lastScanline < 0 - || (lastScanline + width > length)) { - throw new ArrayIndexOutOfBoundsException(); - } - // quick escape if there's nothing to draw - if (width == 0 || height == 0) { - return; - } - // punch down to native for the actual draw - native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha, - paint != null ? paint.mNativePaint : 0); - } - - /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y - */ - public void drawBitmap(int[] colors, int offset, int stride, int x, int y, - int width, int height, boolean hasAlpha, - Paint paint) { - // call through to the common float version - drawBitmap(colors, offset, stride, (float)x, (float)y, width, height, - hasAlpha, paint); - } - - /** - * Draw the bitmap using the specified matrix. - * - * @param bitmap The bitmap to draw - * @param matrix The matrix used to transform the bitmap when it is drawn - * @param paint May be null. The paint used to draw the bitmap - */ - public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) { - nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(), - paint != null ? paint.mNativePaint : 0); - } - - private static void checkRange(int length, int offset, int count) { - if ((offset | count) < 0 || offset + count > length) { - throw new ArrayIndexOutOfBoundsException(); - } - } - - /** - * Draw the bitmap through the mesh, where mesh vertices are evenly - * distributed across the bitmap. There are meshWidth+1 vertices across, and - * meshHeight+1 vertices down. The verts array is accessed in row-major - * order, so that the first meshWidth+1 vertices are distributed across the - * top of the bitmap from left to right. A more general version of this - * methid is drawVertices(). - * - * @param bitmap The bitmap to draw using the mesh - * @param meshWidth The number of columns in the mesh. Nothing is drawn if - * this is 0 - * @param meshHeight The number of rows in the mesh. Nothing is drawn if - * this is 0 - * @param verts Array of x,y pairs, specifying where the mesh should be - * drawn. There must be at least - * (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values - * in the array - * @param vertOffset Number of verts elements to skip before drawing - * @param colors May be null. Specifies a color at each vertex, which is - * interpolated across the cell, and whose values are - * multiplied by the corresponding bitmap colors. If not null, - * there must be at least (meshWidth+1) * (meshHeight+1) + - * colorOffset values in the array. - * @param colorOffset Number of color elements to skip before drawing - * @param paint May be null. The paint used to draw the bitmap - */ - public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, - float[] verts, int vertOffset, - int[] colors, int colorOffset, Paint paint) { - if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) { - throw new ArrayIndexOutOfBoundsException(); - } - if (meshWidth == 0 || meshHeight == 0) { - return; - } - int count = (meshWidth + 1) * (meshHeight + 1); - // we mul by 2 since we need two floats per vertex - checkRange(verts.length, vertOffset, count * 2); - if (colors != null) { - // no mul by 2, since we need only 1 color per vertex - checkRange(colors.length, colorOffset, count); - } - nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight, - verts, vertOffset, colors, colorOffset, - paint != null ? paint.mNativePaint : 0); - } - - public enum VertexMode { - TRIANGLES(0), - TRIANGLE_STRIP(1), - TRIANGLE_FAN(2); - - VertexMode(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * Draw the array of vertices, interpreted as triangles (based on mode). The - * verts array is required, and specifies the x,y pairs for each vertex. If - * texs is non-null, then it is used to specify the coordinate in shader - * coordinates to use at each vertex (the paint must have a shader in this - * case). If there is no texs array, but there is a color array, then each - * color is interpolated across its corresponding triangle in a gradient. If - * both texs and colors arrays are present, then they behave as before, but - * the resulting color at each pixels is the result of multiplying the - * colors from the shader and the color-gradient together. The indices array - * is optional, but if it is present, then it is used to specify the index - * of each triangle, rather than just walking through the arrays in order. - * - * @param mode How to interpret the array of vertices - * @param vertexCount The number of values in the vertices array (and - * corresponding texs and colors arrays if non-null). Each logical - * vertex is two values (x, y), vertexCount must be a multiple of 2. - * @param verts Array of vertices for the mesh - * @param vertOffset Number of values in the verts to skip before drawing. - * @param texs May be null. If not null, specifies the coordinates to sample - * into the current shader (e.g. bitmap tile or gradient) - * @param texOffset Number of values in texs to skip before drawing. - * @param colors May be null. If not null, specifies a color for each - * vertex, to be interpolated across the triangle. - * @param colorOffset Number of values in colors to skip before drawing. - * @param indices If not null, array of indices to reference into the - * vertex (texs, colors) array. - * @param indexCount number of entries in the indices array (if not null). - * @param paint Specifies the shader to use if the texs array is non-null. - */ - public void drawVertices(VertexMode mode, int vertexCount, - float[] verts, int vertOffset, - float[] texs, int texOffset, - int[] colors, int colorOffset, - short[] indices, int indexOffset, - int indexCount, Paint paint) { - checkRange(verts.length, vertOffset, vertexCount); - if (texs != null) { - checkRange(texs.length, texOffset, vertexCount); - } - if (colors != null) { - checkRange(colors.length, colorOffset, vertexCount); - } - if (indices != null) { - checkRange(indices.length, indexOffset, indexCount); - } - nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts, - vertOffset, texs, texOffset, colors, colorOffset, - indices, indexOffset, indexCount, paint.mNativePaint); - } - - /** - * Draw the text, with origin at (x,y), using the specified paint. The - * origin is interpreted based on the Align setting in the paint. - * - * @param text The text to be drawn - * @param x The x-coordinate of the origin of the text being drawn - * @param y The y-coordinate of the origin of the text being drawn - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawText(char[] text, int index, int count, float x, float y, - Paint paint) { - if ((index | count | (index + count) | - (text.length - index - count)) < 0) { - throw new IndexOutOfBoundsException(); - } - native_drawText(mNativeCanvas, text, index, count, x, y, - paint.mNativePaint); - } - - /** - * Draw the text, with origin at (x,y), using the specified paint. The - * origin is interpreted based on the Align setting in the paint. - * - * @param text The text to be drawn - * @param x The x-coordinate of the origin of the text being drawn - * @param y The y-coordinate of the origin of the text being drawn - * @param paint The paint used for the text (e.g. color, size, style) - */ - public native void drawText(String text, float x, float y, Paint paint); - - /** - * Draw the text, with origin at (x,y), using the specified paint. - * The origin is interpreted based on the Align setting in the paint. - * - * @param text The text to be drawn - * @param start The index of the first character in text to draw - * @param end (end - 1) is the index of the last character in text to draw - * @param x The x-coordinate of the origin of the text being drawn - * @param y The y-coordinate of the origin of the text being drawn - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawText(String text, int start, int end, float x, float y, - Paint paint) { - if ((start | end | (end - start) | (text.length() - end)) < 0) { - throw new IndexOutOfBoundsException(); - } - native_drawText(mNativeCanvas, text, start, end, x, y, - paint.mNativePaint); - } - - /** - * Draw the specified range of text, specified by start/end, with its - * origin at (x,y), in the specified Paint. The origin is interpreted - * based on the Align setting in the Paint. - * - * @param text The text to be drawn - * @param start The index of the first character in text to draw - * @param end (end - 1) is the index of the last character in text - * to draw - * @param x The x-coordinate of origin for where to draw the text - * @param y The y-coordinate of origin for where to draw the text - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawText(CharSequence text, int start, int end, float x, - float y, Paint paint) { - if (text instanceof String || text instanceof SpannedString || - text instanceof SpannableString) { - native_drawText(mNativeCanvas, text.toString(), start, end, x, y, - paint.mNativePaint); - } - else if (text instanceof GraphicsOperations) { - ((GraphicsOperations) text).drawText(this, start, end, x, y, - paint); - } - else { - char[] buf = TemporaryBuffer.obtain(end - start); - TextUtils.getChars(text, start, end, buf, 0); - drawText(buf, 0, end - start, x, y, paint); - TemporaryBuffer.recycle(buf); - } - } - - /** - * Draw the text in the array, with each character's origin specified by - * the pos array. - * - * @param text The text to be drawn - * @param index The index of the first character to draw - * @param count The number of characters to draw, starting from index. - * @param pos Array of [x,y] positions, used to position each - * character - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawPosText(char[] text, int index, int count, float[] pos, - Paint paint) { - if (index < 0 || index + count > text.length || count*2 > pos.length) { - throw new IndexOutOfBoundsException(); - } - native_drawPosText(mNativeCanvas, text, index, count, pos, - paint.mNativePaint); - } - - /** - * Draw the text in the array, with each character's origin specified by - * the pos array. - * - * @param text The text to be drawn - * @param pos Array of [x,y] positions, used to position each character - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawPosText(String text, float[] pos, Paint paint) { - if (text.length()*2 > pos.length) { - throw new ArrayIndexOutOfBoundsException(); - } - native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint); - } - - /** - * Draw the text, with origin at (x,y), using the specified paint, along - * the specified path. The paint's Align setting determins where along the - * path to start the text. - * - * @param text The text to be drawn - * @param path The path the text should follow for its baseline - * @param hOffset The distance along the path to add to the text's - * starting position - * @param vOffset The distance above(-) or below(+) the path to position - * the text - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawTextOnPath(char[] text, int index, int count, Path path, - float hOffset, float vOffset, Paint paint) { - if (index < 0 || index + count > text.length) { - throw new ArrayIndexOutOfBoundsException(); - } - native_drawTextOnPath(mNativeCanvas, text, index, count, - path.ni(), hOffset, vOffset, - paint.mNativePaint); - } - - /** - * Draw the text, with origin at (x,y), using the specified paint, along - * the specified path. The paint's Align setting determins where along the - * path to start the text. - * - * @param text The text to be drawn - * @param path The path the text should follow for its baseline - * @param hOffset The distance along the path to add to the text's - * starting position - * @param vOffset The distance above(-) or below(+) the path to position - * the text - * @param paint The paint used for the text (e.g. color, size, style) - */ - public void drawTextOnPath(String text, Path path, float hOffset, - float vOffset, Paint paint) { - if (text.length() > 0) { - native_drawTextOnPath(mNativeCanvas, text, path.ni(), - hOffset, vOffset, paint.mNativePaint); - } - } - - /** - * Save the canvas state, draw the picture, and restore the canvas state. - * This differs from picture.draw(canvas), which does not perform any - * save/restore. - * - * @param picture The picture to be drawn - */ - public void drawPicture(Picture picture) { - picture.endRecording(); - native_drawPicture(mNativeCanvas, picture.ni()); - } - - /** - * Draw the picture, stretched to fit into the dst rectangle. - */ - public void drawPicture(Picture picture, RectF dst) { - save(); - translate(dst.left, dst.top); - if (picture.getWidth() > 0 && picture.getHeight() > 0) { - scale(dst.width() / picture.getWidth(), - dst.height() / picture.getHeight()); - } - drawPicture(picture); - restore(); - } - - /** - * Draw the picture, stretched to fit into the dst rectangle. - */ - public void drawPicture(Picture picture, Rect dst) { - save(); - translate(dst.left, dst.top); - if (picture.getWidth() > 0 && picture.getHeight() > 0) { - scale((float)dst.width() / picture.getWidth(), - (float)dst.height() / picture.getHeight()); - } - drawPicture(picture); - restore(); - } - - protected void finalize() throws Throwable { - super.finalize(); - finalizer(mNativeCanvas); - } - - private static native int initRaster(int nativeBitmapOrZero); - private static native int initGL(); - private static native void native_setBitmap(int nativeCanvas, int bitmap); - private static native void nativeSetViewport(int nCanvas, int w, int h); - private static native int native_saveLayer(int nativeCanvas, RectF bounds, - int paint, int layerFlags); - private static native int native_saveLayer(int nativeCanvas, float l, - float t, float r, float b, - int paint, int layerFlags); - private static native int native_saveLayerAlpha(int nativeCanvas, - RectF bounds, int alpha, - int layerFlags); - private static native int native_saveLayerAlpha(int nativeCanvas, float l, - float t, float r, float b, - int alpha, int layerFlags); - - private static native void native_concat(int nCanvas, int nMatrix); - private static native void native_setMatrix(int nCanvas, int nMatrix); - private static native boolean native_clipRect(int nCanvas, - float left, float top, - float right, float bottom, - int regionOp); - private static native boolean native_clipPath(int nativeCanvas, - int nativePath, - int regionOp); - private static native boolean native_clipRegion(int nativeCanvas, - int nativeRegion, - int regionOp); - private static native void nativeSetDrawFilter(int nativeCanvas, - int nativeFilter); - private static native boolean native_getClipBounds(int nativeCanvas, - Rect bounds); - private static native void native_getCTM(int canvas, int matrix); - private static native boolean native_quickReject(int nativeCanvas, - RectF rect, - int native_edgeType); - private static native boolean native_quickReject(int nativeCanvas, - int path, - int native_edgeType); - private static native boolean native_quickReject(int nativeCanvas, - float left, float top, - float right, float bottom, - int native_edgeType); - private static native void native_drawRGB(int nativeCanvas, int r, int g, - int b); - private static native void native_drawARGB(int nativeCanvas, int a, int r, - int g, int b); - private static native void native_drawColor(int nativeCanvas, int color); - private static native void native_drawColor(int nativeCanvas, int color, - int mode); - private static native void native_drawPaint(int nativeCanvas, int paint); - private static native void native_drawLine(int nativeCanvas, float startX, - float startY, float stopX, - float stopY, int paint); - private static native void native_drawRect(int nativeCanvas, RectF rect, - int paint); - private static native void native_drawRect(int nativeCanvas, float left, - float top, float right, - float bottom, int paint); - private static native void native_drawOval(int nativeCanvas, RectF oval, - int paint); - private static native void native_drawCircle(int nativeCanvas, float cx, - float cy, float radius, - int paint); - private static native void native_drawArc(int nativeCanvas, RectF oval, - float startAngle, float sweep, - boolean useCenter, int paint); - private static native void native_drawRoundRect(int nativeCanvas, - RectF rect, float rx, - float ry, int paint); - private static native void native_drawPath(int nativeCanvas, int path, - int paint); - private native void native_drawBitmap(int nativeCanvas, int bitmap, - float left, float top, - int nativePaintOrZero, boolean autoScale, - float densityScale); - private native void native_drawBitmap(int nativeCanvas, int bitmap, - Rect src, RectF dst, - int nativePaintOrZero); - private static native void native_drawBitmap(int nativeCanvas, int bitmap, - Rect src, Rect dst, - int nativePaintOrZero); - private static native void native_drawBitmap(int nativeCanvas, int[] colors, - int offset, int stride, float x, - float y, int width, int height, - boolean hasAlpha, - int nativePaintOrZero); - private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap, - int nMatrix, int nPaint); - private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap, - int meshWidth, int meshHeight, - float[] verts, int vertOffset, - int[] colors, int colorOffset, int nPaint); - private static native void nativeDrawVertices(int nCanvas, int mode, int n, - float[] verts, int vertOffset, float[] texs, int texOffset, - int[] colors, int colorOffset, short[] indices, - int indexOffset, int indexCount, int nPaint); - - private static native void native_drawText(int nativeCanvas, char[] text, - int index, int count, float x, - float y, int paint); - private static native void native_drawText(int nativeCanvas, String text, - int start, int end, float x, - float y, int paint); - private static native void native_drawPosText(int nativeCanvas, - char[] text, int index, - int count, float[] pos, - int paint); - private static native void native_drawPosText(int nativeCanvas, - String text, float[] pos, - int paint); - private static native void native_drawTextOnPath(int nativeCanvas, - char[] text, int index, - int count, int path, - float hOffset, - float vOffset, int paint); - private static native void native_drawTextOnPath(int nativeCanvas, - String text, int path, - float hOffset, - float vOffset, int paint); - private static native void native_drawPicture(int nativeCanvas, - int nativePicture); - private static native void finalizer(int nativeCanvas); -} diff --git a/graphics/java/android/graphics/Color.java b/graphics/java/android/graphics/Color.java deleted file mode 100644 index 3fc391c..0000000 --- a/graphics/java/android/graphics/Color.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -import java.util.HashMap; -import java.util.Locale; - -/** - * The Color class defines methods for creating and converting color ints. - * Colors are represented as packed ints, made up of 4 bytes: alpha, red, - * green, blue. The values are unpremultiplied, meaning any transparency is - * stored solely in the alpha component, and not in the color components. The - * components are stored as follows (alpha << 24) | (red << 16) | - * (green << 8) | blue. Each component ranges between 0..255 with 0 - * meaning no contribution for that component, and 255 meaning 100% - * contribution. Thus opaque-black would be 0xFF000000 (100% opaque but - * no contributes from red, gree, blue, and opaque-white would be 0xFFFFFFFF - */ -public class Color { - public static final int BLACK = 0xFF000000; - public static final int DKGRAY = 0xFF444444; - public static final int GRAY = 0xFF888888; - public static final int LTGRAY = 0xFFCCCCCC; - public static final int WHITE = 0xFFFFFFFF; - public static final int RED = 0xFFFF0000; - public static final int GREEN = 0xFF00FF00; - public static final int BLUE = 0xFF0000FF; - public static final int YELLOW = 0xFFFFFF00; - public static final int CYAN = 0xFF00FFFF; - public static final int MAGENTA = 0xFFFF00FF; - public static final int TRANSPARENT = 0; - - /** - * Return the alpha component of a color int. This is the same as saying - * color >>> 24 - */ - public static int alpha(int color) { - return color >>> 24; - } - - /** - * Return the red component of a color int. This is the same as saying - * (color >> 16) & 0xFF - */ - public static int red(int color) { - return (color >> 16) & 0xFF; - } - - /** - * Return the green component of a color int. This is the same as saying - * (color >> 8) & 0xFF - */ - public static int green(int color) { - return (color >> 8) & 0xFF; - } - - /** - * Return the blue component of a color int. This is the same as saying - * color & 0xFF - */ - public static int blue(int color) { - return color & 0xFF; - } - - /** - * Return a color-int from red, green, blue components. - * The alpha component is implicity 255 (fully opaque). - * These component values should be [0..255], but there is no - * range check performed, so if they are out of range, the - * returned color is undefined. - * @param red Red component [0..255] of the color - * @param green Green component [0..255] of the color - * @param blue Blue component [0..255] of the color - */ - public static int rgb(int red, int green, int blue) { - return (0xFF << 24) | (red << 16) | (green << 8) | blue; - } - - /** - * Return a color-int from alpha, red, green, blue components. - * These component values should be [0..255], but there is no - * range check performed, so if they are out of range, the - * returned color is undefined. - * @param alpha Alpha component [0..255] of the color - * @param red Red component [0..255] of the color - * @param green Green component [0..255] of the color - * @param blue Blue component [0..255] of the color - */ - public static int argb(int alpha, int red, int green, int blue) { - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } - - /** - * Parse the color string, and return the corresponding color-int. - * If the string cannot be parsed, throws an IllegalArgumentException - * exception. Supported formats are: - * #RRGGBB - * #AARRGGBB - * 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', - * 'yellow', 'lightgray', 'darkgray' - */ - public static int parseColor(String colorString) { - if (colorString.charAt(0) == '#') { - // Use a long to avoid rollovers on #ffXXXXXX - long color = Long.parseLong(colorString.substring(1), 16); - if (colorString.length() == 7) { - // Set the alpha value - color |= 0x00000000ff000000; - } else if (colorString.length() != 9) { - throw new IllegalArgumentException("Unknown color"); - } - return (int)color; - } else { - Integer color = sColorNameMap.get(colorString.toLowerCase(Locale.US)); - if (color != null) { - return color; - } - } - throw new IllegalArgumentException("Unknown color"); - } - - /** - * Convert RGB components to HSV. - * hsv[0] is Hue [0 .. 360) - * hsv[1] is Saturation [0...1] - * hsv[2] is Value [0...1] - * @param red red component value [0..255] - * @param green green component value [0..255] - * @param blue blue component value [0..255] - * @param hsv 3 element array which holds the resulting HSV components. - */ - public static void RGBToHSV(int red, int green, int blue, float hsv[]) { - if (hsv.length < 3) { - throw new RuntimeException("3 components required for hsv"); - } - nativeRGBToHSV(red, green, blue, hsv); - } - - /** - * Convert the argb color to its HSV components. - * hsv[0] is Hue [0 .. 360) - * hsv[1] is Saturation [0...1] - * hsv[2] is Value [0...1] - * @param color the argb color to convert. The alpha component is ignored. - * @param hsv 3 element array which holds the resulting HSV components. - */ - public static void colorToHSV(int color, float hsv[]) { - RGBToHSV((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF, hsv); - } - - /** - * Convert HSV components to an ARGB color. Alpha set to 0xFF. - * hsv[0] is Hue [0 .. 360) - * hsv[1] is Saturation [0...1] - * hsv[2] is Value [0...1] - * If hsv values are out of range, they are pinned. - * @param hsv 3 element array which holds the input HSV components. - * @return the resulting argb color - */ - public static int HSVToColor(float hsv[]) { - return HSVToColor(0xFF, hsv); - } - - /** - * Convert HSV components to an ARGB color. The alpha component is passed - * through unchanged. - * hsv[0] is Hue [0 .. 360) - * hsv[1] is Saturation [0...1] - * hsv[2] is Value [0...1] - * If hsv values are out of range, they are pinned. - * @param alpha the alpha component of the returned argb color. - * @param hsv 3 element array which holds the input HSV components. - * @return the resulting argb color - */ - public static int HSVToColor(int alpha, float hsv[]) { - if (hsv.length < 3) { - throw new RuntimeException("3 components required for hsv"); - } - return nativeHSVToColor(alpha, hsv); - } - - private static native void nativeRGBToHSV(int red, int greed, int blue, - float hsv[]); - private static native int nativeHSVToColor(int alpha, float hsv[]); - - private static final HashMap- * The Draw 9-Patch - * tool offers an extremely handy way to create your NinePatch images, - * using a WYSIWYG graphics editor. - *
- */ -public class NinePatch { - /** - * Create a drawable projection from a bitmap to nine patches. - * - * @param bitmap The bitmap describing the patches. - * @param chunk The 9-patch data chunk describing how the underlying - * bitmap is split apart and drawn. - * @param srcName The name of the source for the bitmap. Might be null. - */ - public NinePatch(Bitmap bitmap, byte[] chunk, String srcName) { - mBitmap = bitmap; - mChunk = chunk; - mSrcName = srcName; - validateNinePatchChunk(mBitmap.ni(), chunk); - } - - /** - * @hide - */ - public NinePatch(NinePatch patch) { - mBitmap = patch.mBitmap; - mChunk = patch.mChunk; - mSrcName = patch.mSrcName; - mPaint = new Paint(patch.mPaint); - validateNinePatchChunk(mBitmap.ni(), mChunk); - } - - public void setPaint(Paint p) { - mPaint = p; - } - - /** - * Draw a bitmap to nine patches. - * - * @param canvas A container for the current matrix and clip used to draw the bitmap. - * @param location Where to draw the bitmap. - */ - public void draw(Canvas canvas, RectF location) { - nativeDraw(canvas.mNativeCanvas, location, - mBitmap.ni(), mChunk, - mPaint != null ? mPaint.mNativePaint : 0); - } - - /** - * Draw a bitmap to nine patches. - * - * @param canvas A container for the current matrix and clip used to draw the bitmap. - * @param location Where to draw the bitmap. - */ - public void draw(Canvas canvas, Rect location) { - nativeDraw(canvas.mNativeCanvas, location, - mBitmap.ni(), mChunk, - mPaint != null ? mPaint.mNativePaint : 0); - } - - /** - * Draw a bitmap to nine patches. - * - * @param canvas A container for the current matrix and clip used to draw the bitmap. - * @param location Where to draw the bitmap. - * @param paint The Paint to draw through. - */ - public void draw(Canvas canvas, Rect location, Paint paint) { - nativeDraw(canvas.mNativeCanvas, location, - mBitmap.ni(), mChunk, paint != null ? paint.mNativePaint : 0); - } - - public int getWidth() { - return mBitmap.getWidth(); - } - - public int getHeight() { - return mBitmap.getHeight(); - } - - public final boolean hasAlpha() { - return mBitmap.hasAlpha(); - } - - public final Region getTransparentRegion(Rect location) { - int r = nativeGetTransparentRegion(mBitmap.ni(), mChunk, location); - return r != 0 ? new Region(r) : null; - } - - public native static boolean isNinePatchChunk(byte[] chunk); - - private final Rect mRect = new Rect(); - private final Bitmap mBitmap; - private final byte[] mChunk; - private Paint mPaint; - private String mSrcName; // Useful for debugging - - private static native void validateNinePatchChunk(int bitmap, byte[] chunk); - private static native void nativeDraw(int canvas_instance, RectF loc, int bitmap_instance, - byte[] c, int paint_instance_or_null); - private static native void nativeDraw(int canvas_instance, Rect loc, int bitmap_instance, - byte[] c, int paint_instance_or_null); - private static native int nativeGetTransparentRegion( - int bitmap, byte[] chunk, Rect location); -} diff --git a/graphics/java/android/graphics/Paint.java b/graphics/java/android/graphics/Paint.java deleted file mode 100644 index 6fac969..0000000 --- a/graphics/java/android/graphics/Paint.java +++ /dev/null @@ -1,1314 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -import android.text.TextUtils; -import android.text.SpannableString; -import android.text.SpannedString; -import android.text.GraphicsOperations; - -/** - * The Paint class holds the style and color information about how to draw - * geometries, text and bitmaps. - */ -public class Paint { - - /*package*/ int mNativePaint; - private ColorFilter mColorFilter; - private MaskFilter mMaskFilter; - private PathEffect mPathEffect; - private Rasterizer mRasterizer; - private Shader mShader; - private Typeface mTypeface; - private Xfermode mXfermode; - - private static final Style[] sStyleArray = { - Style.FILL, Style.STROKE, Style.FILL_AND_STROKE - }; - private static final Cap[] sCapArray = { - Cap.BUTT, Cap.ROUND, Cap.SQUARE - }; - private static final Join[] sJoinArray = { - Join.MITER, Join.ROUND, Join.BEVEL - }; - private static final Align[] sAlignArray = { - Align.LEFT, Align.CENTER, Align.RIGHT - }; - - /** bit mask for the flag enabling antialiasing */ - public static final int ANTI_ALIAS_FLAG = 0x01; - /** bit mask for the flag enabling bitmap filtering */ - public static final int FILTER_BITMAP_FLAG = 0x02; - /** bit mask for the flag enabling dithering */ - public static final int DITHER_FLAG = 0x04; - /** bit mask for the flag enabling underline text */ - public static final int UNDERLINE_TEXT_FLAG = 0x08; - /** bit mask for the flag enabling strike-thru text */ - public static final int STRIKE_THRU_TEXT_FLAG = 0x10; - /** bit mask for the flag enabling fake-bold text */ - public static final int FAKE_BOLD_TEXT_FLAG = 0x20; - /** bit mask for the flag enabling linear-text (no caching) */ - public static final int LINEAR_TEXT_FLAG = 0x40; - /** bit mask for the flag enabling subpixel-text */ - public static final int SUBPIXEL_TEXT_FLAG = 0x80; - /** bit mask for the flag enabling device kerning for text */ - public static final int DEV_KERN_TEXT_FLAG = 0x100; - - // we use this when we first create a paint - private static final int DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG; - - /** - * The Style specifies if the primitive being drawn is filled, - * stroked, or both (in the same color). The default is FILL. - */ - public enum Style { - /** - * Geometry and text drawn with this style will be filled, ignoring all - * stroke-related settings in the paint. - */ - FILL (0), - /** - * Geometry and text drawn with this style will be stroked, respecting - * the stroke-related fields on the paint. - */ - STROKE (1), - /** - * Geometry and text drawn with this style will be both filled and - * stroked at the same time, respecting the stroke-related fields on - * the paint. - */ - FILL_AND_STROKE (2); - - Style(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * The Cap specifies the treatment for the beginning and ending of - * stroked lines and paths. The default is BUTT. - */ - public enum Cap { - /** - * The stroke ends with the path, and does not project beyond it. - */ - BUTT (0), - /** - * The stroke projects out as a square, with the center at the end - * of the path. - */ - ROUND (1), - /** - * The stroke projects out as a semicircle, with the center at the - * end of the path. - */ - SQUARE (2); - - private Cap(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * The Join specifies the treatment where lines and curve segments - * join on a stroked path. The default is MITER. - */ - public enum Join { - /** - * The outer edges of a join meet at a sharp angle - */ - MITER (0), - /** - * The outer edges of a join meet in a circular arc. - */ - ROUND (1), - /** - * The outer edges of a join meet with a straight line - */ - BEVEL (2); - - private Join(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * Align specifies how drawText aligns its text relative to the - * [x,y] coordinates. The default is LEFT. - */ - public enum Align { - /** - * The text is drawn to the right of the x,y origin - */ - LEFT (0), - /** - * The text is drawn centered horizontally on the x,y origin - */ - CENTER (1), - /** - * The text is drawn to the left of the x,y origin - */ - RIGHT (2); - - private Align(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } - - /** - * Create a new paint with default settings. - */ - public Paint() { - this(0); - } - - /** - * Create a new paint with the specified flags. Use setFlags() to change - * these after the paint is created. - * - * @param flags initial flag bits, as if they were passed via setFlags(). - */ - public Paint(int flags) { - mNativePaint = native_init(); - setFlags(flags | DEFAULT_PAINT_FLAGS); - } - - /** - * Create a new paint, initialized with the attributes in the specified - * paint parameter. - * - * @param paint Existing paint used to initialized the attributes of the - * new paint. - */ - public Paint(Paint paint) { - mNativePaint = native_initWithPaint(paint.mNativePaint); - } - - /** Restores the paint to its default settings. */ - public void reset() { - native_reset(mNativePaint); - setFlags(DEFAULT_PAINT_FLAGS); - } - - /** - * Copy the fields from src into this paint. This is equivalent to calling - * get() on all of the src fields, and calling the corresponding set() - * methods on this. - */ - public void set(Paint src) { - if (this != src) { - // copy over the native settings - native_set(mNativePaint, src.mNativePaint); - // copy over our java settings - mColorFilter = src.mColorFilter; - mMaskFilter = src.mMaskFilter; - mPathEffect = src.mPathEffect; - mRasterizer = src.mRasterizer; - mShader = src.mShader; - mTypeface = src.mTypeface; - mXfermode = src.mXfermode; - } - } - - /** - * Return the paint's flags. Use the Flag enum to test flag values. - * - * @return the paint's flags (see enums ending in _Flag for bit masks) - */ - public native int getFlags(); - - /** - * Set the paint's flags. Use the Flag enum to specific flag values. - * - * @param flags The new flag bits for the paint - */ - public native void setFlags(int flags); - - /** - * Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set - * AntiAliasing smooths out the edges of what is being drawn, but is has - * no impact on the interior of the shape. See setDither() and - * setFilterBitmap() to affect how colors are treated. - * - * @return true if the antialias bit is set in the paint's flags. - */ - public final boolean isAntiAlias() { - return (getFlags() & ANTI_ALIAS_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit - * AntiAliasing smooths out the edges of what is being drawn, but is has - * no impact on the interior of the shape. See setDither() and - * setFilterBitmap() to affect how colors are treated. - * - * @param aa true to set the antialias bit in the flags, false to clear it - */ - public native void setAntiAlias(boolean aa); - - /** - * Helper for getFlags(), returning true if DITHER_FLAG bit is set - * Dithering affects how colors that are higher precision than the device - * are down-sampled. No dithering is generally faster, but higher precision - * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to - * distribute the error inherent in this process, to reduce the visual - * artifacts. - * - * @return true if the dithering bit is set in the paint's flags. - */ - public final boolean isDither() { - return (getFlags() & DITHER_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the DITHER_FLAG bit - * Dithering affects how colors that are higher precision than the device - * are down-sampled. No dithering is generally faster, but higher precision - * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to - * distribute the error inherent in this process, to reduce the visual - * artifacts. - * - * @param dither true to set the dithering bit in flags, false to clear it - */ - public native void setDither(boolean dither); - - /** - * Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set - * - * @return true if the lineartext bit is set in the paint's flags - */ - public final boolean isLinearText() { - return (getFlags() & LINEAR_TEXT_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit - * - * @param linearText true to set the linearText bit in the paint's flags, - * false to clear it. - */ - public native void setLinearText(boolean linearText); - - /** - * Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set - * - * @return true if the subpixel bit is set in the paint's flags - */ - public final boolean isSubpixelText() { - return (getFlags() & SUBPIXEL_TEXT_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit - * - * @param subpixelText true to set the subpixelText bit in the paint's - * flags, false to clear it. - */ - public native void setSubpixelText(boolean subpixelText); - - /** - * Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set - * - * @return true if the underlineText bit is set in the paint's flags. - */ - public final boolean isUnderlineText() { - return (getFlags() & UNDERLINE_TEXT_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit - * - * @param underlineText true to set the underlineText bit in the paint's - * flags, false to clear it. - */ - public native void setUnderlineText(boolean underlineText); - - /** - * Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set - * - * @return true if the strikeThruText bit is set in the paint's flags. - */ - public final boolean isStrikeThruText() { - return (getFlags() & STRIKE_THRU_TEXT_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit - * - * @param strikeThruText true to set the strikeThruText bit in the paint's - * flags, false to clear it. - */ - public native void setStrikeThruText(boolean strikeThruText); - - /** - * Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set - * - * @return true if the fakeBoldText bit is set in the paint's flags. - */ - public final boolean isFakeBoldText() { - return (getFlags() & FAKE_BOLD_TEXT_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit - * - * @param fakeBoldText true to set the fakeBoldText bit in the paint's - * flags, false to clear it. - */ - public native void setFakeBoldText(boolean fakeBoldText); - - /** - * Whether or not the bitmap filter is activated. - * Filtering affects the sampling of bitmaps when they are transformed. - * Filtering does not affect how the colors in the bitmap are converted into - * device pixels. That is dependent on dithering and xfermodes. - * - * @see #setFilterBitmap(boolean) setFilterBitmap() - */ - public final boolean isFilterBitmap() { - return (getFlags() & FILTER_BITMAP_FLAG) != 0; - } - - /** - * Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit. - * Filtering affects the sampling of bitmaps when they are transformed. - * Filtering does not affect how the colors in the bitmap are converted into - * device pixels. That is dependent on dithering and xfermodes. - * - * @param filter true to set the FILTER_BITMAP_FLAG bit in the paint's - * flags, false to clear it. - */ - public native void setFilterBitmap(boolean filter); - - /** - * Return the paint's style, used for controlling how primitives' - * geometries are interpreted (except for drawBitmap, which always assumes - * FILL_STYLE). - * - * @return the paint's style setting (Fill, Stroke, StrokeAndFill) - */ - public Style getStyle() { - return sStyleArray[native_getStyle(mNativePaint)]; - } - - /** - * Set the paint's style, used for controlling how primitives' - * geometries are interpreted (except for drawBitmap, which always assumes - * Fill). - * - * @param style The new style to set in the paint - */ - public void setStyle(Style style) { - native_setStyle(mNativePaint, style.nativeInt); - } - - /** - * Return the paint's color. Note that the color is a 32bit value - * containing alpha as well as r,g,b. This 32bit value is not premultiplied, - * meaning that its alpha can be any value, regardless of the values of - * r,g,b. See the Color class for more details. - * - * @return the paint's color (and alpha). - */ - public native int getColor(); - - /** - * Set the paint's color. Note that the color is an int containing alpha - * as well as r,g,b. This 32bit value is not premultiplied, meaning that - * its alpha can be any value, regardless of the values of r,g,b. - * See the Color class for more details. - * - * @param color The new color (including alpha) to set in the paint. - */ - public native void setColor(int color); - - /** - * Helper to getColor() that just returns the color's alpha value. This is - * the same as calling getColor() >>> 24. It always returns a value between - * 0 (completely transparent) and 255 (completely opaque). - * - * @return the alpha component of the paint's color. - */ - public native int getAlpha(); - - /** - * Helper to setColor(), that only assigns the color's alpha value, - * leaving its r,g,b values unchanged. Results are undefined if the alpha - * value is outside of the range [0..255] - * - * @param a set the alpha component [0..255] of the paint's color. - */ - public native void setAlpha(int a); - - /** - * Helper to setColor(), that takes a,r,g,b and constructs the color int - * - * @param a The new alpha component (0..255) of the paint's color. - * @param r The new red component (0..255) of the paint's color. - * @param g The new green component (0..255) of the paint's color. - * @param b The new blue component (0..255) of the paint's color. - */ - public void setARGB(int a, int r, int g, int b) { - setColor((a << 24) | (r << 16) | (g << 8) | b); - } - - /** - * Return the width for stroking. - * - * A value of 0 strokes in hairline mode. - * Hairlines always draws a single pixel independent of the canva's matrix. - * - * @return the paint's stroke width, used whenever the paint's style is - * Stroke or StrokeAndFill. - */ - public native float getStrokeWidth(); - - /** - * Set the width for stroking. - * Pass 0 to stroke in hairline mode. - * Hairlines always draws a single pixel independent of the canva's matrix. - * - * @param width set the paint's stroke width, used whenever the paint's - * style is Stroke or StrokeAndFill. - */ - public native void setStrokeWidth(float width); - - /** - * Return the paint's stroke miter value. Used to control the behavior - * of miter joins when the joins angle is sharp. - * - * @return the paint's miter limit, used whenever the paint's style is - * Stroke or StrokeAndFill. - */ - public native float getStrokeMiter(); - - /** - * Set the paint's stroke miter value. This is used to control the behavior - * of miter joins when the joins angle is sharp. This value must be >= 0. - * - * @param miter set the miter limit on the paint, used whenever the paint's - * style is Stroke or StrokeAndFill. - */ - public native void setStrokeMiter(float miter); - - /** - * Return the paint's Cap, controlling how the start and end of stroked - * lines and paths are treated. - * - * @return the line cap style for the paint, used whenever the paint's - * style is Stroke or StrokeAndFill. - */ - public Cap getStrokeCap() { - return sCapArray[native_getStrokeCap(mNativePaint)]; - } - - /** - * Set the paint's Cap. - * - * @param cap set the paint's line cap style, used whenever the paint's - * style is Stroke or StrokeAndFill. - */ - public void setStrokeCap(Cap cap) { - native_setStrokeCap(mNativePaint, cap.nativeInt); - } - - /** - * Return the paint's stroke join type. - * - * @return the paint's Join. - */ - public Join getStrokeJoin() { - return sJoinArray[native_getStrokeJoin(mNativePaint)]; - } - - /** - * Set the paint's Join. - * - * @param join set the paint's Join, used whenever the paint's style is - * Stroke or StrokeAndFill. - */ - public void setStrokeJoin(Join join) { - native_setStrokeJoin(mNativePaint, join.nativeInt); - } - - /** - * Applies any/all effects (patheffect, stroking) to src, returning the - * result in dst. The result is that drawing src with this paint will be - * the same as drawing dst with a default paint (at least from the - * geometric perspective). - * - * @param src input path - * @param dst output path (may be the same as src) - * @return true if the path should be filled, or false if it should be - * drawn with a hairline (width == 0) - */ - public boolean getFillPath(Path src, Path dst) { - return native_getFillPath(mNativePaint, src.ni(), dst.ni()); - } - - /** - * Get the paint's shader object. - * - * @return the paint's shader (or null) - */ - public Shader getShader() { - return mShader; - } - - /** - * Set or clear the shader object. - * - * Pass null to clear any previous shader. - * As a convenience, the parameter passed is also returned. - * - * @param shader May be null. the new shader to be installed in the paint - * @return shader - */ - public Shader setShader(Shader shader) { - int shaderNative = 0; - if (shader != null) - shaderNative = shader.native_instance; - native_setShader(mNativePaint, shaderNative); - mShader = shader; - return shader; - } - - /** - * Get the paint's colorfilter (maybe be null). - * - * @return the paint's colorfilter (maybe be null) - */ - public ColorFilter getColorFilter() { - return mColorFilter; - } - - /** - * Set or clear the paint's colorfilter, returning the parameter. - * - * @param filter May be null. The new filter to be installed in the paint - * @return filter - */ - public ColorFilter setColorFilter(ColorFilter filter) { - int filterNative = 0; - if (filter != null) - filterNative = filter.native_instance; - native_setColorFilter(mNativePaint, filterNative); - mColorFilter = filter; - return filter; - } - - /** - * Get the paint's xfermode object. - * - * @return the paint's xfermode (or null) - */ - public Xfermode getXfermode() { - return mXfermode; - } - - /** - * Set or clear the xfermode object. - * - * Pass null to clear any previous xfermode. - * As a convenience, the parameter passed is also returned. - * - * @param xfermode May be null. The xfermode to be installed in the paint - * @return xfermode - */ - public Xfermode setXfermode(Xfermode xfermode) { - int xfermodeNative = 0; - if (xfermode != null) - xfermodeNative = xfermode.native_instance; - native_setXfermode(mNativePaint, xfermodeNative); - mXfermode = xfermode; - return xfermode; - } - - /** - * Get the paint's patheffect object. - * - * @return the paint's patheffect (or null) - */ - public PathEffect getPathEffect() { - return mPathEffect; - } - - /** - * Set or clear the patheffect object. - * - * Pass null to clear any previous patheffect. - * As a convenience, the parameter passed is also returned. - * - * @param effect May be null. The patheffect to be installed in the paint - * @return effect - */ - public PathEffect setPathEffect(PathEffect effect) { - int effectNative = 0; - if (effect != null) { - effectNative = effect.native_instance; - } - native_setPathEffect(mNativePaint, effectNative); - mPathEffect = effect; - return effect; - } - - /** - * Get the paint's maskfilter object. - * - * @return the paint's maskfilter (or null) - */ - public MaskFilter getMaskFilter() { - return mMaskFilter; - } - - /** - * Set or clear the maskfilter object. - * - * Pass null to clear any previous maskfilter. - * As a convenience, the parameter passed is also returned. - * - * @param maskfilter May be null. The maskfilter to be installed in the - * paint - * @return maskfilter - */ - public MaskFilter setMaskFilter(MaskFilter maskfilter) { - int maskfilterNative = 0; - if (maskfilter != null) { - maskfilterNative = maskfilter.native_instance; - } - native_setMaskFilter(mNativePaint, maskfilterNative); - mMaskFilter = maskfilter; - return maskfilter; - } - - /** - * Get the paint's typeface object. - * - * The typeface object identifies which font to use when drawing or - * measuring text. - * - * @return the paint's typeface (or null) - */ - public Typeface getTypeface() { - return mTypeface; - } - - /** - * Set or clear the typeface object. - * - * Pass null to clear any previous typeface. - * As a convenience, the parameter passed is also returned. - * - * @param typeface May be null. The typeface to be installed in the paint - * @return typeface - */ - public Typeface setTypeface(Typeface typeface) { - int typefaceNative = 0; - if (typeface != null) { - typefaceNative = typeface.native_instance; - } - native_setTypeface(mNativePaint, typefaceNative); - mTypeface = typeface; - return typeface; - } - - /** - * Get the paint's rasterizer (or null). - * - * The raster controls/modifies how paths/text are turned into alpha masks. - * - * @return the paint's rasterizer (or null) - */ - public Rasterizer getRasterizer() { - return mRasterizer; - } - - /** - * Set or clear the rasterizer object. - * - * Pass null to clear any previous rasterizer. - * As a convenience, the parameter passed is also returned. - * - * @param rasterizer May be null. The new rasterizer to be installed in - * the paint. - * @return rasterizer - */ - public Rasterizer setRasterizer(Rasterizer rasterizer) { - int rasterizerNative = 0; - if (rasterizer != null) { - rasterizerNative = rasterizer.native_instance; - } - native_setRasterizer(mNativePaint, rasterizerNative); - mRasterizer = rasterizer; - return rasterizer; - } - - /** - * Temporary API to expose layer drawing. This draws a shadow layer below - * the main layer, with the specified offset and color, and blur radius. - * If radius is 0, then the shadow layer is removed. - */ - public native void setShadowLayer(float radius, float dx, float dy, - int color); - - /** - * Temporary API to clear the shadow layer. - */ - public void clearShadowLayer() { - setShadowLayer(0, 0, 0, 0); - } - - /** - * Return the paint's Align value for drawing text. This controls how the - * text is positioned relative to its origin. LEFT align means that all of - * the text will be drawn to the right of its origin (i.e. the origin - * specifieds the LEFT edge of the text) and so on. - * - * @return the paint's Align value for drawing text. - */ - public Align getTextAlign() { - return sAlignArray[native_getTextAlign(mNativePaint)]; - } - - /** - * Set the paint's text alignment. This controls how the - * text is positioned relative to its origin. LEFT align means that all of - * the text will be drawn to the right of its origin (i.e. the origin - * specifieds the LEFT edge of the text) and so on. - * - * @param align set the paint's Align value for drawing text. - */ - public void setTextAlign(Align align) { - native_setTextAlign(mNativePaint, align.nativeInt); - } - - /** - * Return the paint's text size. - * - * @return the paint's text size. - */ - public native float getTextSize(); - - /** - * Set the paint's text size. This value must be > 0 - * - * @param textSize set the paint's text size. - */ - public native void setTextSize(float textSize); - - /** - * Return the paint's horizontal scale factor for text. The default value - * is 1.0. - * - * @return the paint's scale factor in X for drawing/measuring text - */ - public native float getTextScaleX(); - - /** - * Set the paint's horizontal scale factor for text. The default value - * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will - * stretch the text narrower. - * - * @param scaleX set the paint's scale in X for drawing/measuring text. - */ - public native void setTextScaleX(float scaleX); - - /** - * Return the paint's horizontal skew factor for text. The default value - * is 0. - * - * @return the paint's skew factor in X for drawing text. - */ - public native float getTextSkewX(); - - /** - * Set the paint's horizontal skew factor for text. The default value - * is 0. For approximating oblique text, use values around -0.25. - * - * @param skewX set the paint's skew factor in X for drawing text. - */ - public native void setTextSkewX(float skewX); - - /** - * Return the distance above (negative) the baseline (ascent) based on the - * current typeface and text size. - * - * @return the distance above (negative) the baseline (ascent) based on the - * current typeface and text size. - */ - public native float ascent(); - - /** - * Return the distance below (positive) the baseline (descent) based on the - * current typeface and text size. - * - * @return the distance below (positive) the baseline (descent) based on - * the current typeface and text size. - */ - public native float descent(); - - /** - * Class that describes the various metrics for a font at a given text size. - * Remember, Y values increase going down, so those values will be positive, - * and values that measure distances going up will be negative. This class - * is returned by getFontMetrics(). - */ - public static class FontMetrics { - /** - * The maximum distance above the baseline for the tallest glyph in - * the font at a given text size. - */ - public float top; - /** - * The recommended distance above the baseline for singled spaced text. - */ - public float ascent; - /** - * The recommended distance below the baseline for singled spaced text. - */ - public float descent; - /** - * The maximum distance below the baseline for the lowest glyph in - * the font at a given text size. - */ - public float bottom; - /** - * The recommended additional space to add between lines of text. - */ - public float leading; - } - - /** - * Return the font's recommended interline spacing, given the Paint's - * settings for typeface, textSize, etc. If metrics is not null, return the - * fontmetric values in it. - * - * @param metrics If this object is not null, its fields are filled with - * the appropriate values given the paint's text attributes. - * @return the font's recommended interline spacing. - */ - public native float getFontMetrics(FontMetrics metrics); - - /** - * Allocates a new FontMetrics object, and then calls getFontMetrics(fm) - * with it, returning the object. - */ - public FontMetrics getFontMetrics() { - FontMetrics fm = new FontMetrics(); - getFontMetrics(fm); - return fm; - } - - /** - * Convenience method for callers that want to have FontMetrics values as - * integers. - */ - public static class FontMetricsInt { - public int top; - public int ascent; - public int descent; - public int bottom; - public int leading; - - @Override public String toString() { - return "FontMetricsInt: top=" + top + " ascent=" + ascent + - " descent=" + descent + " bottom=" + bottom + - " leading=" + leading; - } - } - - /** - * Return the font's interline spacing, given the Paint's settings for - * typeface, textSize, etc. If metrics is not null, return the fontmetric - * values in it. Note: all values have been converted to integers from - * floats, in such a way has to make the answers useful for both spacing - * and clipping. If you want more control over the rounding, call - * getFontMetrics(). - * - * @return the font's interline spacing. - */ - public native int getFontMetricsInt(FontMetricsInt fmi); - - public FontMetricsInt getFontMetricsInt() { - FontMetricsInt fm = new FontMetricsInt(); - getFontMetricsInt(fm); - return fm; - } - - /** - * Return the recommend line spacing based on the current typeface and - * text size. - * - * @return recommend line spacing based on the current typeface and - * text size. - */ - public float getFontSpacing() { - return getFontMetrics(null); - } - - /** - * Return the width of the text. - * - * @param text The text to measure - * @param index The index of the first character to start measuring - * @param count THe number of characters to measure, beginning with start - * @return The width of the text - */ - public native float measureText(char[] text, int index, int count); - - /** - * Return the width of the text. - * - * @param text The text to measure - * @param start The index of the first character to start measuring - * @param end 1 beyond the index of the last character to measure - * @return The width of the text - */ - public native float measureText(String text, int start, int end); - - /** - * Return the width of the text. - * - * @param text The text to measure - * @return The width of the text - */ - public native float measureText(String text); - - /** - * Return the width of the text. - * - * @param text The text to measure - * @param start The index of the first character to start measuring - * @param end 1 beyond the index of the last character to measure - * @return The width of the text - */ - public float measureText(CharSequence text, int start, int end) { - if (text instanceof String) { - return measureText((String)text, start, end); - } - if (text instanceof SpannedString || - text instanceof SpannableString) { - return measureText(text.toString(), start, end); - } - if (text instanceof GraphicsOperations) { - return ((GraphicsOperations)text).measureText(start, end, this); - } - - char[] buf = TemporaryBuffer.obtain(end - start); - TextUtils.getChars(text, start, end, buf, 0); - float result = measureText(buf, 0, end - start); - TemporaryBuffer.recycle(buf); - return result; - } - - /** - * Measure the text, stopping early if the measured width exceeds maxWidth. - * Return the number of chars that were measured, and if measuredWidth is - * not null, return in it the actual width measured. - * - * @param text The text to measure - * @param index The offset into text to begin measuring at - * @param count The number of maximum number of entries to measure. If count - * is negative, then the characters before index are measured - * in reverse order. This allows for measuring the end of - * string. - * @param maxWidth The maximum width to accumulate. - * @param measuredWidth Optional. If not null, returns the actual width - * measured. - * @return The number of chars that were measured. Will always be <= - * abs(count). - */ - public native int breakText(char[] text, int index, int count, - float maxWidth, float[] measuredWidth); - - /** - * Measure the text, stopping early if the measured width exceeds maxWidth. - * Return the number of chars that were measured, and if measuredWidth is - * not null, return in it the actual width measured. - * - * @param text The text to measure - * @param start The offset into text to begin measuring at - * @param end The end of the text slice to measure. - * @param measureForwards If true, measure forwards, starting at start. - * Otherwise, measure backwards, starting with end. - * @param maxWidth The maximum width to accumulate. - * @param measuredWidth Optional. If not null, returns the actual width - * measured. - * @return The number of chars that were measured. Will always be <= - * abs(end - start). - */ - public int breakText(CharSequence text, int start, int end, - boolean measureForwards, - float maxWidth, float[] measuredWidth) { - if (start == 0 && text instanceof String && end == text.length()) { - return breakText((String) text, measureForwards, maxWidth, - measuredWidth); - } - - char[] buf = TemporaryBuffer.obtain(end - start); - int result; - - TextUtils.getChars(text, start, end, buf, 0); - - if (measureForwards) { - result = breakText(buf, 0, end - start, maxWidth, measuredWidth); - } else { - result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth); - } - - TemporaryBuffer.recycle(buf); - return result; - } - - /** - * Measure the text, stopping early if the measured width exceeds maxWidth. - * Return the number of chars that were measured, and if measuredWidth is - * not null, return in it the actual width measured. - * - * @param text The text to measure - * @param measureForwards If true, measure forwards, starting at index. - * Otherwise, measure backwards, starting with the - * last character in the string. - * @param maxWidth The maximum width to accumulate. - * @param measuredWidth Optional. If not null, returns the actual width - * measured. - * @return The number of chars that were measured. Will always be <= - * abs(count). - */ - public native int breakText(String text, boolean measureForwards, - float maxWidth, float[] measuredWidth); - - /** - * Return the advance widths for the characters in the string. - * - * @param text The text to measure - * @param index The index of the first char to to measure - * @param count The number of chars starting with index to measure - * @param widths array to receive the advance widths of the characters. - * Must be at least a large as count. - * @return the actual number of widths returned. - */ - public int getTextWidths(char[] text, int index, int count, - float[] widths) { - if ((index | count) < 0 || index + count > text.length - || count > widths.length) { - throw new ArrayIndexOutOfBoundsException(); - } - return native_getTextWidths(mNativePaint, text, index, count, widths); - } - - /** - * Return the advance widths for the characters in the string. - * - * @param text The text to measure - * @param start The index of the first char to to measure - * @param end The end of the text slice to measure - * @param widths array to receive the advance widths of the characters. - * Must be at least a large as (end - start). - * @return the actual number of widths returned. - */ - public int getTextWidths(CharSequence text, int start, int end, - float[] widths) { - if (text instanceof String) { - return getTextWidths((String) text, start, end, widths); - } - if (text instanceof SpannedString || - text instanceof SpannableString) { - return getTextWidths(text.toString(), start, end, widths); - } - if (text instanceof GraphicsOperations) { - return ((GraphicsOperations) text).getTextWidths(start, end, - widths, this); - } - - char[] buf = TemporaryBuffer.obtain(end - start); - TextUtils.getChars(text, start, end, buf, 0); - int result = getTextWidths(buf, 0, end - start, widths); - TemporaryBuffer.recycle(buf); - return result; - } - - /** - * Return the advance widths for the characters in the string. - * - * @param text The text to measure - * @param start The index of the first char to to measure - * @param end The end of the text slice to measure - * @param widths array to receive the advance widths of the characters. - * Must be at least a large as the text. - * @return the number of unichars in the specified text. - */ - public int getTextWidths(String text, int start, int end, float[] widths) { - if ((start | end | (end - start) | (text.length() - end)) < 0) { - throw new IndexOutOfBoundsException(); - } - if (end - start > widths.length) { - throw new ArrayIndexOutOfBoundsException(); - } - return native_getTextWidths(mNativePaint, text, start, end, widths); - } - - /** - * Return the advance widths for the characters in the string. - * - * @param text The text to measure - * @param widths array to receive the advance widths of the characters. - * Must be at least a large as the text. - * @return the number of unichars in the specified text. - */ - public int getTextWidths(String text, float[] widths) { - return getTextWidths(text, 0, text.length(), widths); - } - - /** - * Return the path (outline) for the specified text. - * Note: just like Canvas.drawText, this will respect the Align setting in - * the paint. - * - * @param text The text to retrieve the path from - * @param index The index of the first character in text - * @param count The number of characterss starting with index - * @param x The x coordinate of the text's origin - * @param y The y coordinate of the text's origin - * @param path The path to receive the data describing the text. Must - * be allocated by the caller. - */ - public void getTextPath(char[] text, int index, int count, - float x, float y, Path path) { - if ((index | count) < 0 || index + count > text.length) { - throw new ArrayIndexOutOfBoundsException(); - } - native_getTextPath(mNativePaint, text, index, count, x, y, path.ni()); - } - - /** - * Return the path (outline) for the specified text. - * Note: just like Canvas.drawText, this will respect the Align setting - * in the paint. - * - * @param text The text to retrieve the path from - * @param start The first character in the text - * @param end 1 past the last charcter in the text - * @param x The x coordinate of the text's origin - * @param y The y coordinate of the text's origin - * @param path The path to receive the data describing the text. Must - * be allocated by the caller. - */ - public void getTextPath(String text, int start, int end, - float x, float y, Path path) { - if ((start | end | (end - start) | (text.length() - end)) < 0) { - throw new IndexOutOfBoundsException(); - } - native_getTextPath(mNativePaint, text, start, end, x, y, path.ni()); - } - - /** - * Return in bounds (allocated by the caller) the smallest rectangle that - * encloses all of the characters, with an implied origin at (0,0). - * - * @param text String to measure and return its bounds - * @param start Index of the first char in the string to measure - * @param end 1 past the last char in the string measure - * @param bounds Returns the unioned bounds of all the text. Must be - * allocated by the caller. - */ - public void getTextBounds(String text, int start, int end, Rect bounds) { - if ((start | end | (end - start) | (text.length() - end)) < 0) { - throw new IndexOutOfBoundsException(); - } - if (bounds == null) { - throw new NullPointerException("need bounds Rect"); - } - nativeGetStringBounds(mNativePaint, text, start, end, bounds); - } - - /** - * Return in bounds (allocated by the caller) the smallest rectangle that - * encloses all of the characters, with an implied origin at (0,0). - * - * @param text Array of chars to measure and return their unioned bounds - * @param index Index of the first char in the array to measure - * @param count The number of chars, beginning at index, to measure - * @param bounds Returns the unioned bounds of all the text. Must be - * allocated by the caller. - */ - public void getTextBounds(char[] text, int index, int count, Rect bounds) { - if ((index | count) < 0 || index + count > text.length) { - throw new ArrayIndexOutOfBoundsException(); - } - if (bounds == null) { - throw new NullPointerException("need bounds Rect"); - } - nativeGetCharArrayBounds(mNativePaint, text, index, count, bounds); - } - - protected void finalize() throws Throwable { - finalizer(mNativePaint); - } - - private static native int native_init(); - private static native int native_initWithPaint(int paint); - private static native void native_reset(int native_object); - private static native void native_set(int native_dst, int native_src); - private static native int native_getStyle(int native_object); - private static native void native_setStyle(int native_object, int style); - private static native int native_getStrokeCap(int native_object); - private static native void native_setStrokeCap(int native_object, int cap); - private static native int native_getStrokeJoin(int native_object); - private static native void native_setStrokeJoin(int native_object, - int join); - private static native boolean native_getFillPath(int native_object, - int src, int dst); - private static native int native_setShader(int native_object, int shader); - private static native int native_setColorFilter(int native_object, - int filter); - private static native int native_setXfermode(int native_object, - int xfermode); - private static native int native_setPathEffect(int native_object, - int effect); - private static native int native_setMaskFilter(int native_object, - int maskfilter); - private static native int native_setTypeface(int native_object, - int typeface); - private static native int native_setRasterizer(int native_object, - int rasterizer); - - private static native int native_getTextAlign(int native_object); - private static native void native_setTextAlign(int native_object, - int align); - - private static native float native_getFontMetrics(int native_paint, - FontMetrics metrics); - private static native int native_getTextWidths(int native_object, - char[] text, int index, int count, float[] widths); - private static native int native_getTextWidths(int native_object, - String text, int start, int end, float[] widths); - private static native void native_getTextPath(int native_object, - char[] text, int index, int count, float x, float y, int path); - private static native void native_getTextPath(int native_object, - String text, int start, int end, float x, float y, int path); - private static native void nativeGetStringBounds(int nativePaint, - String text, int start, int end, Rect bounds); - private static native void nativeGetCharArrayBounds(int nativePaint, - char[] text, int index, int count, Rect bounds); - private static native void finalizer(int nativePaint); -} - diff --git a/graphics/java/android/graphics/PaintFlagsDrawFilter.java b/graphics/java/android/graphics/PaintFlagsDrawFilter.java deleted file mode 100644 index 0f0d03d..0000000 --- a/graphics/java/android/graphics/PaintFlagsDrawFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PaintFlagsDrawFilter extends DrawFilter { - - /** - * Subclass of DrawFilter that affects every paint by first clearing - * the specified clearBits in the paint's flags, and then setting the - * specified setBits in the paint's flags. - * - * @param clearBits These bits will be cleared in the paint's flags - * @param setBits These bits will be set in the paint's flags - */ - public PaintFlagsDrawFilter(int clearBits, int setBits) { - // our native constructor can return 0, if the specified bits - // are effectively a no-op - mNativeInt = nativeConstructor(clearBits, setBits); - } - - private static native int nativeConstructor(int clearBits, int setBits); -} - diff --git a/graphics/java/android/graphics/Path.java b/graphics/java/android/graphics/Path.java deleted file mode 100644 index c3f63d7..0000000 --- a/graphics/java/android/graphics/Path.java +++ /dev/null @@ -1,599 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -/** - * The Path class encapsulates compound (multiple contour) geometric paths - * consisting of straight line segments, quadratic curves, and cubic curves. - * It can be drawn with canvas.drawPath(path, paint), either filled or stroked - * (based on the paint's Style), or it can be used for clipping or to draw - * text on a path. - */ -public class Path { - - /** - * Create an empty path - */ - public Path() { - mNativePath = init1(); - } - - /** - * Create a new path, copying the contents from the src path. - * - * @param src The path to copy from when initializing the new path - */ - public Path(Path src) { - int valNative = 0; - if (src != null) { - valNative = src.mNativePath; - } - mNativePath = init2(valNative); - } - - /** - * Clear any lines and curves from the path, making it empty. - * This does NOT change the fill-type setting. - */ - public void reset() { - native_reset(mNativePath); - } - - /** - * Rewinds the path: clears any lines and curves from the path but - * keeps the internal data structure for faster reuse. - */ - public void rewind() { - native_rewind(mNativePath); - } - - /** Replace the contents of this with the contents of src. - */ - public void set(Path src) { - if (this != src) { - native_set(mNativePath, src.mNativePath); - } - } - - /** Enum for the ways a path may be filled - */ - public enum FillType { - // these must match the values in SkPath.h - WINDING (0), - EVEN_ODD (1), - INVERSE_WINDING (2), - INVERSE_EVEN_ODD(3); - - FillType(int ni) { - nativeInt = ni; - } - final int nativeInt; - } - - // these must be in the same order as their native values - private static final FillType[] sFillTypeArray = { - FillType.WINDING, - FillType.EVEN_ODD, - FillType.INVERSE_WINDING, - FillType.INVERSE_EVEN_ODD - }; - - /** - * Return the path's fill type. This defines how "inside" is - * computed. The default value is WINDING. - * - * @return the path's fill type - */ - public FillType getFillType() { - return sFillTypeArray[native_getFillType(mNativePath)]; - } - - /** - * Set the path's fill type. This defines how "inside" is computed. - * - * @param ft The new fill type for this path - */ - public void setFillType(FillType ft) { - native_setFillType(mNativePath, ft.nativeInt); - } - - /** - * Returns true if the filltype is one of the INVERSE variants - * - * @return true if the filltype is one of the INVERSE variants - */ - public boolean isInverseFillType() { - final int ft = native_getFillType(mNativePath); - return (ft & 2) != 0; - } - - /** - * Toggles the INVERSE state of the filltype - */ - public void toggleInverseFillType() { - int ft = native_getFillType(mNativePath); - ft ^= 2; - native_setFillType(mNativePath, ft); - } - - /** - * Returns true if the path is empty (contains no lines or curves) - * - * @return true if the path is empty (contains no lines or curves) - */ - public boolean isEmpty() { - return native_isEmpty(mNativePath); - } - - /** - * Returns true if the path specifies a rectangle. If so, and if rect is - * not null, set rect to the bounds of the path. If the path does not - * specify a rectangle, return false and ignore rect. - * - * @param rect If not null, returns the bounds of the path if it specifies - * a rectangle - * @return true if the path specifies a rectangle - */ - public boolean isRect(RectF rect) { - return native_isRect(mNativePath, rect); - } - - /** - * Compute the bounds of the path, and write the answer into bounds. If the - * path contains 0 or 1 points, the bounds is set to (0,0,0,0) - * - * @param bounds Returns the computed bounds of the path - * @param exact If true, return the exact (but slower) bounds, else return - * just the bounds of all control points - */ - public void computeBounds(RectF bounds, boolean exact) { - // 1-exact, 0-fast correspond to the values in SkPath.h - native_computeBounds(mNativePath, bounds, exact ? 1 : 0); - } - - /** - * Hint to the path to prepare for adding more points. This can allow the - * path to more efficiently allocate its storage. - * - * @param extraPtCount The number of extra points that may be added to this - * path - */ - public void incReserve(int extraPtCount) { - native_incReserve(mNativePath, extraPtCount); - } - - /** - * Set the beginning of the next contour to the point (x,y). - * - * @param x The x-coordinate of the start of a new contour - * @param y The y-coordinate of the start of a new contour - */ - public void moveTo(float x, float y) { - native_moveTo(mNativePath, x, y); - } - - /** - * Set the beginning of the next contour relative to the last point on the - * previous contour. If there is no previous contour, this is treated the - * same as moveTo(). - * - * @param dx The amount to add to the x-coordinate of the end of the - * previous contour, to specify the start of a new contour - * @param dy The amount to add to the y-coordinate of the end of the - * previous contour, to specify the start of a new contour - */ - public void rMoveTo(float dx, float dy) { - native_rMoveTo(mNativePath, dx, dy); - } - - /** - * Add a line from the last point to the specified point (x,y). - * If no moveTo() call has been made for this contour, the first point is - * automatically set to (0,0). - * - * @param x The x-coordinate of the end of a line - * @param y The y-coordinate of the end of a line - */ - public void lineTo(float x, float y) { - native_lineTo(mNativePath, x, y); - } - - /** - * Same as lineTo, but the coordinates are considered relative to the last - * point on this contour. If there is no previous point, then a moveTo(0,0) - * is inserted automatically. - * - * @param dx The amount to add to the x-coordinate of the previous point on - * this contour, to specify a line - * @param dy The amount to add to the y-coordinate of the previous point on - * this contour, to specify a line - */ - public void rLineTo(float dx, float dy) { - native_rLineTo(mNativePath, dx, dy); - } - - /** - * Add a quadratic bezier from the last point, approaching control point - * (x1,y1), and ending at (x2,y2). If no moveTo() call has been made for - * this contour, the first point is automatically set to (0,0). - * - * @param x1 The x-coordinate of the control point on a quadratic curve - * @param y1 The y-coordinate of the control point on a quadratic curve - * @param x2 The x-coordinate of the end point on a quadratic curve - * @param y2 The y-coordinate of the end point on a quadratic curve - */ - public void quadTo(float x1, float y1, float x2, float y2) { - native_quadTo(mNativePath, x1, y1, x2, y2); - } - - /** - * Same as quadTo, but the coordinates are considered relative to the last - * point on this contour. If there is no previous point, then a moveTo(0,0) - * is inserted automatically. - * - * @param dx1 The amount to add to the x-coordinate of the last point on - * this contour, for the control point of a quadratic curve - * @param dy1 The amount to add to the y-coordinate of the last point on - * this contour, for the control point of a quadratic curve - * @param dx2 The amount to add to the x-coordinate of the last point on - * this contour, for the end point of a quadratic curve - * @param dy2 The amount to add to the y-coordinate of the last point on - * this contour, for the end point of a quadratic curve - */ - public void rQuadTo(float dx1, float dy1, float dx2, float dy2) { - native_rQuadTo(mNativePath, dx1, dy1, dx2, dy2); - } - - /** - * Add a cubic bezier from the last point, approaching control points - * (x1,y1) and (x2,y2), and ending at (x3,y3). If no moveTo() call has been - * made for this contour, the first point is automatically set to (0,0). - * - * @param x1 The x-coordinate of the 1st control point on a cubic curve - * @param y1 The y-coordinate of the 1st control point on a cubic curve - * @param x2 The x-coordinate of the 2nd control point on a cubic curve - * @param y2 The y-coordinate of the 2nd control point on a cubic curve - * @param x3 The x-coordinate of the end point on a cubic curve - * @param y3 The y-coordinate of the end point on a cubic curve - */ - public void cubicTo(float x1, float y1, float x2, float y2, - float x3, float y3) { - native_cubicTo(mNativePath, x1, y1, x2, y2, x3, y3); - } - - /** - * Same as cubicTo, but the coordinates are considered relative to the - * current point on this contour. If there is no previous point, then a - * moveTo(0,0) is inserted automatically. - */ - public void rCubicTo(float x1, float y1, float x2, float y2, - float x3, float y3) { - native_rCubicTo(mNativePath, x1, y1, x2, y2, x3, y3); - } - - /** - * Append the specified arc to the path as a new contour. If the start of - * the path is different from the path's current last point, then an - * automatic lineTo() is added to connect the current contour to the - * start of the arc. However, if the path is empty, then we call moveTo() - * with the first point of the arc. The sweep angle is tread mod 360. - * - * @param oval The bounds of oval defining shape and size of the arc - * @param startAngle Starting angle (in degrees) where the arc begins - * @param sweepAngle Sweep angle (in degrees) measured clockwise, treated - * mod 360. - * @param forceMoveTo If true, always begin a new contour with the arc - */ - public void arcTo(RectF oval, float startAngle, float sweepAngle, - boolean forceMoveTo) { - native_arcTo(mNativePath, oval, startAngle, sweepAngle, forceMoveTo); - } - - /** - * Append the specified arc to the path as a new contour. If the start of - * the path is different from the path's current last point, then an - * automatic lineTo() is added to connect the current contour to the - * start of the arc. However, if the path is empty, then we call moveTo() - * with the first point of the arc. - * - * @param oval The bounds of oval defining shape and size of the arc - * @param startAngle Starting angle (in degrees) where the arc begins - * @param sweepAngle Sweep angle (in degrees) measured clockwise - */ - public void arcTo(RectF oval, float startAngle, float sweepAngle) { - native_arcTo(mNativePath, oval, startAngle, sweepAngle, false); - } - - /** - * Close the current contour. If the current point is not equal to the - * first point of the contour, a line segment is automatically added. - */ - public void close() { - native_close(mNativePath); - } - - /** - * Specifies how closed shapes (e.g. rects, ovals) are oriented when they - * are added to a path. - */ - public enum Direction { - /** clockwise */ - CW (0), // must match enum in SkPath.h - /** counter-clockwise */ - CCW (1); // must match enum in SkPath.h - - Direction(int ni) { - nativeInt = ni; - } - final int nativeInt; - } - - /** - * Add a closed rectangle contour to the path - * - * @param rect The rectangle to add as a closed contour to the path - * @param dir The direction to wind the rectangle's contour - */ - public void addRect(RectF rect, Direction dir) { - if (rect == null) { - throw new NullPointerException("need rect parameter"); - } - native_addRect(mNativePath, rect, dir.nativeInt); - } - - /** - * Add a closed rectangle contour to the path - * - * @param left The left side of a rectangle to add to the path - * @param top The top of a rectangle to add to the path - * @param right The right side of a rectangle to add to the path - * @param bottom The bottom of a rectangle to add to the path - * @param dir The direction to wind the rectangle's contour - */ - public void addRect(float left, float top, float right, float bottom, - Direction dir) { - native_addRect(mNativePath, left, top, right, bottom, dir.nativeInt); - } - - /** - * Add a closed oval contour to the path - * - * @param oval The bounds of the oval to add as a closed contour to the path - * @param dir The direction to wind the oval's contour - */ - public void addOval(RectF oval, Direction dir) { - if (oval == null) { - throw new NullPointerException("need oval parameter"); - } - native_addOval(mNativePath, oval, dir.nativeInt); - } - - /** - * Add a closed circle contour to the path - * - * @param x The x-coordinate of the center of a circle to add to the path - * @param y The y-coordinate of the center of a circle to add to the path - * @param radius The radius of a circle to add to the path - * @param dir The direction to wind the circle's contour - */ - public void addCircle(float x, float y, float radius, Direction dir) { - native_addCircle(mNativePath, x, y, radius, dir.nativeInt); - } - - /** - * Add the specified arc to the path as a new contour. - * - * @param oval The bounds of oval defining the shape and size of the arc - * @param startAngle Starting angle (in degrees) where the arc begins - * @param sweepAngle Sweep angle (in degrees) measured clockwise - */ - public void addArc(RectF oval, float startAngle, float sweepAngle) { - if (oval == null) { - throw new NullPointerException("need oval parameter"); - } - native_addArc(mNativePath, oval, startAngle, sweepAngle); - } - - /** - * Add a closed round-rectangle contour to the path - * - * @param rect The bounds of a round-rectangle to add to the path - * @param rx The x-radius of the rounded corners on the round-rectangle - * @param ry The y-radius of the rounded corners on the round-rectangle - * @param dir The direction to wind the round-rectangle's contour - */ - public void addRoundRect(RectF rect, float rx, float ry, Direction dir) { - if (rect == null) { - throw new NullPointerException("need rect parameter"); - } - native_addRoundRect(mNativePath, rect, rx, ry, dir.nativeInt); - } - - /** - * Add a closed round-rectangle contour to the path. Each corner receives - * two radius values [X, Y]. The corners are ordered top-left, top-right, - * bottom-right, bottom-left - * - * @param rect The bounds of a round-rectangle to add to the path - * @param radii Array of 8 values, 4 pairs of [X,Y] radii - * @param dir The direction to wind the round-rectangle's contour - */ - public void addRoundRect(RectF rect, float[] radii, Direction dir) { - if (rect == null) { - throw new NullPointerException("need rect parameter"); - } - if (radii.length < 8) { - throw new ArrayIndexOutOfBoundsException("radii[] needs 8 values"); - } - native_addRoundRect(mNativePath, rect, radii, dir.nativeInt); - } - - /** - * Add a copy of src to the path, offset by (dx,dy) - * - * @param src The path to add as a new contour - * @param dx The amount to translate the path in X as it is added - */ - public void addPath(Path src, float dx, float dy) { - native_addPath(mNativePath, src.mNativePath, dx, dy); - } - - /** - * Add a copy of src to the path - * - * @param src The path that is appended to the current path - */ - public void addPath(Path src) { - native_addPath(mNativePath, src.mNativePath); - } - - /** - * Add a copy of src to the path, transformed by matrix - * - * @param src The path to add as a new contour - */ - public void addPath(Path src, Matrix matrix) { - native_addPath(mNativePath, src.mNativePath, matrix.native_instance); - } - - /** - * Offset the path by (dx,dy), returning true on success - * - * @param dx The amount in the X direction to offset the entire path - * @param dy The amount in the Y direction to offset the entire path - * @param dst The translated path is written here. If this is null, then - * the original path is modified. - */ - public void offset(float dx, float dy, Path dst) { - int dstNative = 0; - if (dst != null) { - dstNative = dst.mNativePath; - } - native_offset(mNativePath, dx, dy, dstNative); - } - - /** - * Offset the path by (dx,dy), returning true on success - * - * @param dx The amount in the X direction to offset the entire path - * @param dy The amount in the Y direction to offset the entire path - */ - public void offset(float dx, float dy) { - native_offset(mNativePath, dx, dy); - } - - /** - * Sets the last point of the path. - * - * @param dx The new X coordinate for the last point - * @param dy The new Y coordinate for the last point - */ - public void setLastPoint(float dx, float dy) { - native_setLastPoint(mNativePath, dx, dy); - } - - /** - * Transform the points in this path by matrix, and write the answer - * into dst. If dst is null, then the the original path is modified. - * - * @param matrix The matrix to apply to the path - * @param dst The transformed path is written here. If dst is null, - * then the the original path is modified - */ - public void transform(Matrix matrix, Path dst) { - int dstNative = 0; - if (dst != null) { - dstNative = dst.mNativePath; - } - native_transform(mNativePath, matrix.native_instance, dstNative); - } - - /** - * Transform the points in this path by matrix. - * - * @param matrix The matrix to apply to the path - */ - public void transform(Matrix matrix) { - native_transform(mNativePath, matrix.native_instance); - } - - protected void finalize() throws Throwable { - try { - finalizer(mNativePath); - } finally { - super.finalize(); - } - } - - /*package*/ final int ni() { - return mNativePath; - } - - private static native int init1(); - private static native int init2(int nPath); - private static native void native_reset(int nPath); - private static native void native_rewind(int nPath); - private static native void native_set(int native_dst, int native_src); - private static native int native_getFillType(int nPath); - private static native void native_setFillType(int nPath, int ft); - private static native boolean native_isEmpty(int nPath); - private static native boolean native_isRect(int nPath, RectF rect); - private static native void native_computeBounds(int nPath, RectF bounds, - int btype); - private static native void native_incReserve(int nPath, int extraPtCount); - private static native void native_moveTo(int nPath, float x, float y); - private static native void native_rMoveTo(int nPath, float dx, float dy); - private static native void native_lineTo(int nPath, float x, float y); - private static native void native_rLineTo(int nPath, float dx, float dy); - private static native void native_quadTo(int nPath, float x1, float y1, - float x2, float y2); - private static native void native_rQuadTo(int nPath, float dx1, float dy1, - float dx2, float dy2); - private static native void native_cubicTo(int nPath, float x1, float y1, - float x2, float y2, float x3, float y3); - private static native void native_rCubicTo(int nPath, float x1, float y1, - float x2, float y2, float x3, float y3); - private static native void native_arcTo(int nPath, RectF oval, - float startAngle, float sweepAngle, boolean forceMoveTo); - private static native void native_close(int nPath); - private static native void native_addRect(int nPath, RectF rect, int dir); - private static native void native_addRect(int nPath, float left, float top, - float right, float bottom, int dir); - private static native void native_addOval(int nPath, RectF oval, int dir); - private static native void native_addCircle(int nPath, float x, float y, - float radius, int dir); - private static native void native_addArc(int nPath, RectF oval, - float startAngle, float sweepAngle); - private static native void native_addRoundRect(int nPath, RectF rect, - float rx, float ry, int dir); - private static native void native_addRoundRect(int nPath, RectF r, - float[] radii, int dir); - private static native void native_addPath(int nPath, int src, float dx, - float dy); - private static native void native_addPath(int nPath, int src); - private static native void native_addPath(int nPath, int src, int matrix); - private static native void native_offset(int nPath, float dx, float dy, - int dst_path); - private static native void native_offset(int nPath, float dx, float dy); - private static native void native_setLastPoint(int nPath, float dx, float dy); - private static native void native_transform(int nPath, int matrix, - int dst_path); - private static native void native_transform(int nPath, int matrix); - private static native void finalizer(int nPath); - - private final int mNativePath; -} diff --git a/graphics/java/android/graphics/PathDashPathEffect.java b/graphics/java/android/graphics/PathDashPathEffect.java deleted file mode 100644 index e8ad5fd..0000000 --- a/graphics/java/android/graphics/PathDashPathEffect.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PathDashPathEffect extends PathEffect { - - public enum Style { - TRANSLATE(0), //!< translate the shape to each position - ROTATE(1), //!< rotate the shape about its center - MORPH(2); //!< transform each point, and turn lines into curves - - Style(int value) { - native_style = value; - } - int native_style; - } - - /** - * Dash the drawn path by stamping it with the specified shape. This only - * applies to drawings when the paint's style is STROKE or STROKE_AND_FILL. - * If the paint's style is FILL, then this effect is ignored. The paint's - * strokeWidth does not affect the results. - * @param shape The path to stamp along - * @param advance spacing between each stamp of shape - * @param phase amount to offset before the first shape is stamped - * @param style how to transform the shape at each position as it is stamped - */ - public PathDashPathEffect(Path shape, float advance, float phase, - Style style) { - native_instance = nativeCreate(shape.ni(), advance, phase, - style.native_style); - } - - private static native int nativeCreate(int native_path, float advance, - float phase, int native_style); -} - diff --git a/graphics/java/android/graphics/PathEffect.java b/graphics/java/android/graphics/PathEffect.java deleted file mode 100644 index 9b2cd66..0000000 --- a/graphics/java/android/graphics/PathEffect.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -/** - * PathEffect is the base class for objects in the Paint that affect - * the geometry of a drawing primitive before it is transformed by the - * canvas' matrix and drawn. - */ -public class PathEffect { - - protected void finalize() throws Throwable { - nativeDestructor(native_instance); - } - - private static native void nativeDestructor(int native_patheffect); - int native_instance; -} diff --git a/graphics/java/android/graphics/PathMeasure.java b/graphics/java/android/graphics/PathMeasure.java deleted file mode 100644 index 98f7821..0000000 --- a/graphics/java/android/graphics/PathMeasure.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PathMeasure { - - /** - * Create an empty PathMeasure object. To uses this to measure the length - * of a path, and/or to find the position and tangent along it, call - * setPath. - * - * Note that once a path is associated with the measure object, it is - * undefined if the path is subsequently modified and the the measure object - * is used. If the path is modified, you must call setPath with the path. - */ - public PathMeasure() { - native_instance = native_create(0, false); - } - - /** - * Create a PathMeasure object associated with the specified path object - * (already created and specified). The meansure object can now return the - * path's length, and the position and tangent of any position along the - * path. - * - * Note that once a path is associated with the measure object, it is - * undefined if the path is subsequently modified and the the measure object - * is used. If the path is modified, you must call setPath with the path. - * - * @param path The path that will be measured by this object - * @param forceClosed If true, then the path will be considered as "closed" - * even if its contour was not explicitly closed. - */ - public PathMeasure(Path path, boolean forceClosed) { - // note: the native side makes a copy of path, so we don't need a java - // reference to it here, since it's fine if it gets GC'd - native_instance = native_create(path != null ? path.ni() : 0, - forceClosed); - } - - /** - * Assign a new path, or null to have none. - */ - public void setPath(Path path, boolean forceClosed) { - // note: the native side makes a copy of path, so we don't need a java - // reference to it here, since it's fine if it gets GC'd - native_setPath(native_instance, - path != null ? path.ni() : 0, - forceClosed); - } - - /** - * Return the total length of the current contour, or 0 if no path is - * associated with this measure object. - */ - public float getLength() { - return native_getLength(native_instance); - } - - /** - * Pins distance to 0 <= distance <= getLength(), and then computes the - * corresponding position and tangent. Returns false if there is no path, - * or a zero-length path was specified, in which case position and tangent - * are unchanged. - * - * @param distance The distance along the current contour to sample - * @param pos If not null, eturns the sampled position (x==[0], y==[1]) - * @param tan If not null, returns the sampled tangent (x==[0], y==[1]) - * @return false if there was no path associated with this measure object - */ - public boolean getPosTan(float distance, float pos[], float tan[]) { - if (pos != null && pos.length < 2 || - tan != null && tan.length < 2) { - throw new ArrayIndexOutOfBoundsException(); - } - return native_getPosTan(native_instance, distance, pos, tan); - } - - public static final int POSITION_MATRIX_FLAG = 0x01; // must match flags in SkPathMeasure.h - public static final int TANGENT_MATRIX_FLAG = 0x02; // must match flags in SkPathMeasure.h - - /** - * Pins distance to 0 <= distance <= getLength(), and then computes the - * corresponding matrix. Returns false if there is no path, or a zero-length - * path was specified, in which case matrix is unchanged. - * - * @param distance The distance along the associated path - * @param matrix Allocated by the caller, this is set to the transformation - * associated with the position and tangent at the specified distance - * @param flags Specified what aspects should be returned in the matrix. - */ - public boolean getMatrix(float distance, Matrix matrix, int flags) { - return native_getMatrix(native_instance, distance, matrix.native_instance, flags); - } - - /** - * Given a start and stop distance, return in dst the intervening - * segment(s). If the segment is zero-length, return false, else return - * true. startD and stopD are pinned to legal values (0..getLength()). - * If startD <= stopD then return false (and leave dst untouched). - * Begin the segment with a moveTo if startWithMoveTo is true - */ - public boolean getSegment(float startD, float stopD, Path dst, boolean startWithMoveTo) { - return native_getSegment(native_instance, startD, stopD, dst.ni(), startWithMoveTo); - } - - /** - * Return true if the current contour is closed() - */ - public boolean isClosed() { - return native_isClosed(native_instance); - } - - /** - * Move to the next contour in the path. Return true if one exists, or - * false if we're done with the path. - */ - public boolean nextContour() { - return native_nextContour(native_instance); - } - - protected void finalize() throws Throwable { - native_destroy(native_instance); - } - - private static native int native_create(int native_path, boolean forceClosed); - private static native void native_setPath(int native_instance, int native_path, boolean forceClosed); - private static native float native_getLength(int native_instance); - private static native boolean native_getPosTan(int native_instance, float distance, float pos[], float tan[]); - private static native boolean native_getMatrix(int native_instance, float distance, int native_matrix, int flags); - private static native boolean native_getSegment(int native_instance, float startD, float stopD, int native_path, boolean startWithMoveTo); - private static native boolean native_isClosed(int native_instance); - private static native boolean native_nextContour(int native_instance); - private static native void native_destroy(int native_instance); - - /* package */private final int native_instance; -} - diff --git a/graphics/java/android/graphics/Picture.java b/graphics/java/android/graphics/Picture.java deleted file mode 100644 index bbb2dbf..0000000 --- a/graphics/java/android/graphics/Picture.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - * A picture records drawing calls (via the canvas returned by beginRecording) - * and can then play them back (via picture.draw(canvas) or canvas.drawPicture). - * The picture's contents can also be written to a stream, and then later - * restored to a new picture (via writeToStream / createFromStream). For most - * content (esp. text, lines, rectangles), drawing a sequence from a picture can - * be faster than the equivalent API calls, since the picture performs its - * playback without incurring any java-call overhead. - */ -public class Picture { - private Canvas mRecordingCanvas; - private final int mNativePicture; - - private static final int WORKING_STREAM_STORAGE = 16 * 1024; - - public Picture() { - this(nativeConstructor(0)); - } - - /** - * Create a picture by making a copy of what has already been recorded in - * src. The contents of src are unchanged, and if src changes later, those - * changes will not be reflected in this picture. - */ - public Picture(Picture src) { - this(nativeConstructor(src != null ? src.mNativePicture : 0)); - } - - /** - * To record a picture, call beginRecording() and then draw into the Canvas - * that is returned. Nothing we appear on screen, but all of the draw - * commands (e.g. drawRect(...)) will be recorded. To stop recording, call - * endRecording(). At this point the Canvas that was returned must no longer - * be referenced, and nothing should be drawn into it. - */ - public Canvas beginRecording(int width, int height) { - int ni = nativeBeginRecording(mNativePicture, width, height); - mRecordingCanvas = new RecordingCanvas(this, ni); - return mRecordingCanvas; - } - - /** - * Call endRecording when the picture is built. After this call, the picture - * may be drawn, but the canvas that was returned by beginRecording must not - * be referenced anymore. This is automatically called if Picture.draw() or - * Canvas.drawPicture() is called. - */ - public void endRecording() { - if (mRecordingCanvas != null) { - mRecordingCanvas = null; - nativeEndRecording(mNativePicture); - } - } - - /** - * Get the width of the picture as passed to beginRecording. This - * does not reflect (per se) the content of the picture. - */ - public native int getWidth(); - - /** - * Get the height of the picture as passed to beginRecording. This - * does not reflect (per se) the content of the picture. - */ - public native int getHeight(); - - /** - * Draw this picture on the canvas. The picture may have the side effect - * of changing the matrix and clip of the canvas. - * - * @param canvas The picture is drawn to this canvas - */ - public void draw(Canvas canvas) { - if (mRecordingCanvas != null) { - endRecording(); - } - nativeDraw(canvas.mNativeCanvas, mNativePicture); - } - - /** - * Create a new picture (already recorded) from the data in the stream. This - * data was generated by a previous call to writeToStream(). - */ - public static Picture createFromStream(InputStream stream) { - return new Picture( - nativeCreateFromStream(stream, new byte[WORKING_STREAM_STORAGE])); - } - - /** - * Write the picture contents to a stream. The data can be used to recreate - * the picture in this or another process by calling createFromStream. - */ - public void writeToStream(OutputStream stream) { - // do explicit check before calling the native method - if (stream == null) { - throw new NullPointerException(); - } - if (!nativeWriteToStream(mNativePicture, stream, - new byte[WORKING_STREAM_STORAGE])) { - throw new RuntimeException(); - } - } - - protected void finalize() throws Throwable { - nativeDestructor(mNativePicture); - } - - /*package*/ final int ni() { - return mNativePicture; - } - - private Picture(int nativePicture) { - if (nativePicture == 0) { - throw new RuntimeException(); - } - mNativePicture = nativePicture; - } - - // return empty picture if src is 0, or a copy of the native src - private static native int nativeConstructor(int nativeSrcOr0); - private static native int nativeCreateFromStream(InputStream stream, - byte[] storage); - private static native int nativeBeginRecording(int nativeCanvas, - int w, int h); - private static native void nativeEndRecording(int nativeCanvas); - private static native void nativeDraw(int nativeCanvas, int nativePicture); - private static native boolean nativeWriteToStream(int nativePicture, - OutputStream stream, byte[] storage); - private static native void nativeDestructor(int nativePicture); - - private static class RecordingCanvas extends Canvas { - private final Picture mPicture; - - public RecordingCanvas(Picture pict, int nativeCanvas) { - super(nativeCanvas); - mPicture = pict; - } - - @Override - public void setBitmap(Bitmap bitmap) { - throw new RuntimeException( - "Cannot call setBitmap on a picture canvas"); - } - - @Override - public void drawPicture(Picture picture) { - if (mPicture == picture) { - throw new RuntimeException( - "Cannot draw a picture into its recording canvas"); - } - super.drawPicture(picture); - } - } -} - diff --git a/graphics/java/android/graphics/PixelFormat.java b/graphics/java/android/graphics/PixelFormat.java deleted file mode 100644 index 159accc..0000000 --- a/graphics/java/android/graphics/PixelFormat.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PixelFormat -{ - /* these constants need to match those - in ui/PixelFormat.h & pixelflinger/format.h */ - - public static final int UNKNOWN = 0; - - /** System chooses a format that supports translucency (many alpha bits) */ - public static final int TRANSLUCENT = -3; - - /** - * System chooses a format that supports transparency - * (at least 1 alpha bit) - */ - public static final int TRANSPARENT = -2; - - /** System chooses an opaque format (no alpha bits required) */ - public static final int OPAQUE = -1; - - public static final int RGBA_8888 = 1; - public static final int RGBX_8888 = 2; - public static final int RGB_888 = 3; - public static final int RGB_565 = 4; - - public static final int RGBA_5551 = 6; - public static final int RGBA_4444 = 7; - public static final int A_8 = 8; - public static final int L_8 = 9; - public static final int LA_88 = 0xA; - public static final int RGB_332 = 0xB; - - /** - * YCbCr formats, used for video. These are not necessarily supported - * by the hardware. - */ - public static final int YCbCr_422_SP= 0x10; - public static final int YCbCr_420_SP= 0x11; - - /** - * Encoded formats. These are not necessarily supported by the hardware. - */ - public static final int JPEG = 0x100; - - /* - * We use a class initializer to allow the native code to cache some - * field offsets. - */ - native private static void nativeClassInit(); - static { nativeClassInit(); } - - public static native void getPixelFormatInfo(int format, PixelFormat info); - public static boolean formatHasAlpha(int format) { - switch (format) { - case PixelFormat.A_8: - case PixelFormat.LA_88: - case PixelFormat.RGBA_4444: - case PixelFormat.RGBA_5551: - case PixelFormat.RGBA_8888: - case PixelFormat.TRANSLUCENT: - case PixelFormat.TRANSPARENT: - return true; - } - return false; - } - - public int bytesPerPixel; - public int bitsPerPixel; -} diff --git a/graphics/java/android/graphics/PixelXorXfermode.java b/graphics/java/android/graphics/PixelXorXfermode.java deleted file mode 100644 index 18d15cf..0000000 --- a/graphics/java/android/graphics/PixelXorXfermode.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -/** - * PixelXorXfermode implements a simple pixel xor (op ^ src ^ dst). - * This transformation does not follow premultiplied conventions, therefore - * this mode *always* returns an opaque color (alpha == 255). Thus it is - * not really usefull for operating on blended colors. - */ -public class PixelXorXfermode extends Xfermode { - - public PixelXorXfermode(int opColor) { - native_instance = nativeCreate(opColor); - } - - private static native int nativeCreate(int opColor); -} diff --git a/graphics/java/android/graphics/Point.java b/graphics/java/android/graphics/Point.java deleted file mode 100644 index c351444..0000000 --- a/graphics/java/android/graphics/Point.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - - -/** - * Point holds two integer coordinates - */ -public class Point { - public int x; - public int y; - - public Point() {} - - public Point(int x, int y) { - this.x = x; - this.y = y; - } - - public Point(Point src) { - this.x = src.x; - this.y = src.y; - } - - /** - * Set the point's x and y coordinates - */ - public void set(int x, int y) { - this.x = x; - this.y = y; - } - - /** - * Negate the point's coordinates - */ - public final void negate() { - x = -x; - y = -y; - } - - /** - * Offset the point's coordinates by dx, dy - */ - public final void offset(int dx, int dy) { - x += dx; - y += dy; - } - - /** - * Returns true if the point's coordinates equal (x,y) - */ - public final boolean equals(int x, int y) { - return this.x == x && this.y == y; - } - - @Override public boolean equals(Object o) { - if (o instanceof Point) { - Point p = (Point) o; - return this.x == p.x && this.y == p.y; - } - return false; - } - - @Override public int hashCode() { - return x * 32713 + y; - } - - @Override public String toString() { - return "Point(" + x + ", " + y+ ")"; - } -} diff --git a/graphics/java/android/graphics/PointF.java b/graphics/java/android/graphics/PointF.java deleted file mode 100644 index 0f045a1..0000000 --- a/graphics/java/android/graphics/PointF.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -import android.util.FloatMath; - - -/** - * PointF holds two float coordinates - */ -public class PointF { - public float x; - public float y; - - public PointF() {} - - public PointF(float x, float y) { - this.x = x; - this.y = y; - } - - public PointF(Point p) { - this.x = p.x; - this.y = p.y; - } - - /** - * Set the point's x and y coordinates - */ - public final void set(float x, float y) { - this.x = x; - this.y = y; - } - - /** - * Set the point's x and y coordinates to the coordinates of p - */ - public final void set(PointF p) { - this.x = p.x; - this.y = p.y; - } - - public final void negate() { - x = -x; - y = -y; - } - - public final void offset(float dx, float dy) { - x += dx; - y += dy; - } - - /** - * Returns true if the point's coordinates equal (x,y) - */ - public final boolean equals(float x, float y) { - return this.x == x && this.y == y; - } - - /** - * Return the euclidian distance from (0,0) to the point - */ - public final float length() { - return length(x, y); - } - - /** - * Returns the euclidian distance from (0,0) to (x,y) - */ - public static float length(float x, float y) { - return FloatMath.sqrt(x * x + y * y); - } -} - diff --git a/graphics/java/android/graphics/PorterDuff.java b/graphics/java/android/graphics/PorterDuff.java deleted file mode 100644 index 3904234..0000000 --- a/graphics/java/android/graphics/PorterDuff.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PorterDuff { - - // these value must match their native equivalents. See SkPorterDuff.h - public enum Mode { - /** [0, 0] */ - CLEAR (0), - /** [Sa, Sc] */ - SRC (1), - /** [Da, Dc] */ - DST (2), - /** [Sa + (1 - Sa)*Da, Rc = Sc + (1 - Sa)*Dc] */ - SRC_OVER (3), - /** [Sa + (1 - Sa)*Da, Rc = Dc + (1 - Da)*Sc] */ - DST_OVER (4), - /** [Sa * Da, Sc * Da] */ - SRC_IN (5), - /** [Sa * Da, Sa * Dc] */ - DST_IN (6), - /** [Sa * (1 - Da), Sc * (1 - Da)] */ - SRC_OUT (7), - /** [Da * (1 - Sa), Dc * (1 - Sa)] */ - DST_OUT (8), - /** [Da, Sc * Da + (1 - Sa) * Dc] */ - SRC_ATOP (9), - /** [Sa, Sa * Dc + Sc * (1 - Da)] */ - DST_ATOP (10), - /** [Sa + Da - 2 * Sa * Da, Sc * (1 - Da) + (1 - Sa) * Dc] */ - XOR (11), - /** [Sa + Da - Sa*Da, - Sc*(1 - Da) + Dc*(1 - Sa) + min(Sc, Dc)] */ - DARKEN (12), - /** [Sa + Da - Sa*Da, - Sc*(1 - Da) + Dc*(1 - Sa) + max(Sc, Dc)] */ - LIGHTEN (13), - /** [Sa * Da, Sc * Dc] */ - MULTIPLY (14), - /** [Sa + Da - Sa * Da, Sc + Dc - Sc * Dc] */ - SCREEN (15); - - Mode(int nativeInt) { - this.nativeInt = nativeInt; - } - final int nativeInt; - } -} diff --git a/graphics/java/android/graphics/PorterDuffColorFilter.java b/graphics/java/android/graphics/PorterDuffColorFilter.java deleted file mode 100644 index 06724bd..0000000 --- a/graphics/java/android/graphics/PorterDuffColorFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PorterDuffColorFilter extends ColorFilter { - /** - * Create a colorfilter that uses the specified color and porter-duff mode. - * - * @param srcColor The source color used with the specified - * porter-duff mode - * @param mode The porter-duff mode that is applied - */ - public PorterDuffColorFilter(int srcColor, PorterDuff.Mode mode) { - native_instance = native_CreatePorterDuffFilter(srcColor, - mode.nativeInt); - } - - private static native int native_CreatePorterDuffFilter(int srcColor, - int porterDuffMode); -} diff --git a/graphics/java/android/graphics/PorterDuffXfermode.java b/graphics/java/android/graphics/PorterDuffXfermode.java deleted file mode 100644 index cb127fd..0000000 --- a/graphics/java/android/graphics/PorterDuffXfermode.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class PorterDuffXfermode extends Xfermode { - /** - * Create an xfermode that uses the specified porter-duff mode. - * - * @param mode The porter-duff mode that is applied - */ - public PorterDuffXfermode(PorterDuff.Mode mode) { - native_instance = nativeCreateXfermode(mode.nativeInt); - } - - private static native int nativeCreateXfermode(int mode); -} diff --git a/graphics/java/android/graphics/RadialGradient.java b/graphics/java/android/graphics/RadialGradient.java deleted file mode 100644 index b4e902d..0000000 --- a/graphics/java/android/graphics/RadialGradient.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -public class RadialGradient extends Shader { - - /** Create a shader that draws a radial gradient given the center and radius. - @param x The x-coordinate of the center of the radius - @param y The y-coordinate of the center of the radius - @param radius Must be positive. The radius of the circle for this gradient - @param colors The colors to be distributed between the center and edge of the circle - @param positions May be NULL. The relative position of - each corresponding color in the colors array. If this is NULL, - the the colors are distributed evenly between the center and edge of the circle. - @param tile The Shader tiling mode - */ - public RadialGradient(float x, float y, float radius, - int colors[], float positions[], TileMode tile) { - if (radius <= 0) { - throw new IllegalArgumentException("radius must be > 0"); - } - if (colors.length < 2) { - throw new IllegalArgumentException("needs >= 2 number of colors"); - } - if (positions != null && colors.length != positions.length) { - throw new IllegalArgumentException("color and position arrays must be of equal length"); - } - native_instance = nativeCreate1(x, y, radius, colors, positions, tile.nativeInt); - } - - /** Create a shader that draws a radial gradient given the center and radius. - @param x The x-coordinate of the center of the radius - @param y The y-coordinate of the center of the radius - @param radius Must be positive. The radius of the circle for this gradient - @param color0 The color at the center of the circle. - @param color1 The color at the edge of the circle. - @param tile The Shader tiling mode - */ - public RadialGradient(float x, float y, float radius, - int color0, int color1, TileMode tile) { - if (radius <= 0) { - throw new IllegalArgumentException("radius must be > 0"); - } - native_instance = nativeCreate2(x, y, radius, color0, color1, tile.nativeInt); - } - - private static native int nativeCreate1(float x, float y, float radius, - int colors[], float positions[], int tileMode); - private static native int nativeCreate2(float x, float y, float radius, - int color0, int color1, int tileMode); -} - diff --git a/graphics/java/android/graphics/Rasterizer.java b/graphics/java/android/graphics/Rasterizer.java deleted file mode 100644 index feb5f0c..0000000 --- a/graphics/java/android/graphics/Rasterizer.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// This file was generated from the C++ include file: SkRasterizer.h -// Any changes made to this file will be discarded by the build. -// To change this file, either edit the include, or device/tools/gluemaker/main.cpp, -// or one of the auxilary file specifications in device/tools/gluemaker. - -package android.graphics; - -public class Rasterizer { - - protected void finalize() throws Throwable { - finalizer(native_instance); - } - - private static native void finalizer(int native_instance); - - int native_instance; -} diff --git a/graphics/java/android/graphics/Rect.aidl b/graphics/java/android/graphics/Rect.aidl deleted file mode 100644 index 09edbfe..0000000 --- a/graphics/java/android/graphics/Rect.aidl +++ /dev/null @@ -1,20 +0,0 @@ -/* //device/java/android/android/graphics/Rect.aidl -** -** Copyright 2007, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - -package android.graphics; - -parcelable Rect; diff --git a/graphics/java/android/graphics/Rect.java b/graphics/java/android/graphics/Rect.java deleted file mode 100644 index 2005344..0000000 --- a/graphics/java/android/graphics/Rect.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Rect holds four integer coordinates for a rectangle. The rectangle is - * represented by the coordinates of its 4 edges (left, top, right bottom). - * These fields can be accessed directly. Use width() and height() to retrieve - * the rectangle's width and height. Note: most methods do not check to see that - * the coordinates are sorted correctly (i.e. left <= right and top <= bottom). - */ -public final class Rect implements Parcelable { - public int left; - public int top; - public int right; - public int bottom; - - /** - * Create a new empty Rect. All coordinates are initialized to 0. - */ - public Rect() {} - - /** - * Create a new rectangle with the specified coordinates. Note: no range - * checking is performed, so the caller must ensure that left <= right and - * top <= bottom. - * - * @param left The X coordinate of the left side of the rectagle - * @param top The Y coordinate of the top of the rectangle - * @param right The X coordinate of the right side of the rectagle - * @param bottom The Y coordinate of the bottom of the rectangle - */ - public Rect(int left, int top, int right, int bottom) { - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; - } - - /** - * Create a new rectangle, initialized with the values in the specified - * rectangle (which is left unmodified). - * - * @param r The rectangle whose coordinates are copied into the new - * rectangle. - */ - public Rect(Rect r) { - left = r.left; - top = r.top; - right = r.right; - bottom = r.bottom; - } - - public boolean equals(Object obj) { - Rect r = (Rect) obj; - if (r != null) { - return left == r.left && top == r.top && right == r.right - && bottom == r.bottom; - } - return false; - } - - public String toString() { - return "Rect(" + left + ", " + top + " - " + right + ", " + bottom + ")"; - } - - /** - * Return a string representation of the rectangle in a compact form. - */ - public String toShortString() { - return "[" + left + "," + top + "][" + right + "," + bottom + "]"; - } - - /** - * Returns true if the rectangle is empty (left >= right or top >= bottom) - */ - public final boolean isEmpty() { - return left >= right || top >= bottom; - } - - /** - * @return the rectangle's width. This does not check for a valid rectangle - * (i.e. left <= right) so the result may be negative. - */ - public final int width() { - return right - left; - } - - /** - * @return the rectangle's height. This does not check for a valid rectangle - * (i.e. top <= bottom) so the result may be negative. - */ - public final int height() { - return bottom - top; - } - - /** - * @return the horizontal center of the rectangle. If the computed value - * is fractional, this method returns the largest integer that is - * less than the computed value. - */ - public final int centerX() { - return (left + right) >> 1; - } - - /** - * @return the vertical center of the rectangle. If the computed value - * is fractional, this method returns the largest integer that is - * less than the computed value. - */ - public final int centerY() { - return (top + bottom) >> 1; - } - - /** - * @return the exact horizontal center of the rectangle as a float. - */ - public final float exactCenterX() { - return (left + right) * 0.5f; - } - - /** - * @return the exact vertical center of the rectangle as a float. - */ - public final float exactCenterY() { - return (top + bottom) * 0.5f; - } - - /** - * Set the rectangle to (0,0,0,0) - */ - public void setEmpty() { - left = right = top = bottom = 0; - } - - /** - * Set the rectangle's coordinates to the specified values. Note: no range - * checking is performed, so it is up to the caller to ensure that - * left <= right and top <= bottom. - * - * @param left The X coordinate of the left side of the rectagle - * @param top The Y coordinate of the top of the rectangle - * @param right The X coordinate of the right side of the rectagle - * @param bottom The Y coordinate of the bottom of the rectangle - */ - public void set(int left, int top, int right, int bottom) { - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; - } - - /** - * Copy the coordinates from src into this rectangle. - * - * @param src The rectangle whose coordinates are copied into this - * rectangle. - */ - public void set(Rect src) { - this.left = src.left; - this.top = src.top; - this.right = src.right; - this.bottom = src.bottom; - } - - /** - * Offset the rectangle by adding dx to its left and right coordinates, and - * adding dy to its top and bottom coordinates. - * - * @param dx The amount to add to the rectangle's left and right coordinates - * @param dy The amount to add to the rectangle's top and bottom coordinates - */ - public void offset(int dx, int dy) { - left += dx; - top += dy; - right += dx; - bottom += dy; - } - - /** - * Offset the rectangle to a specific (left, top) position, - * keeping its width and height the same. - * - * @param newLeft The new "left" coordinate for the rectangle - * @param newTop The new "top" coordinate for the rectangle - */ - public void offsetTo(int newLeft, int newTop) { - right += newLeft - left; - bottom += newTop - top; - left = newLeft; - top = newTop; - } - - /** - * Inset the rectangle by (dx,dy). If dx is positive, then the sides are - * moved inwards, making the rectangle narrower. If dx is negative, then the - * sides are moved outwards, making the rectangle wider. The same holds true - * for dy and the top and bottom. - * - * @param dx The amount to add(subtract) from the rectangle's left(right) - * @param dy The amount to add(subtract) from the rectangle's top(bottom) - */ - public void inset(int dx, int dy) { - left += dx; - top += dy; - right -= dx; - bottom -= dy; - } - - /** - * Returns true if (x,y) is inside the rectangle. The left and top are - * considered to be inside, while the right and bottom are not. This means - * that for a x,y to be contained: left <= x < right and top <= y < bottom. - * An empty rectangle never contains any point. - * - * @param x The X coordinate of the point being tested for containment - * @param y The Y coordinate of the point being tested for containment - * @return true iff (x,y) are contained by the rectangle, where containment - * means left <= x < right and top <= y < bottom - */ - public boolean contains(int x, int y) { - return left < right && top < bottom // check for empty first - && x >= left && x < right && y >= top && y < bottom; - } - - /** - * Returns true iff the 4 specified sides of a rectangle are inside or equal - * to this rectangle. i.e. is this rectangle a superset of the specified - * rectangle. An empty rectangle never contains another rectangle. - * - * @param left The left side of the rectangle being tested for containment - * @param top The top of the rectangle being tested for containment - * @param right The right side of the rectangle being tested for containment - * @param bottom The bottom of the rectangle being tested for containment - * @return true iff the the 4 specified sides of a rectangle are inside or - * equal to this rectangle - */ - public boolean contains(int left, int top, int right, int bottom) { - // check for empty first - return this.left < this.right && this.top < this.bottom - // now check for containment - && this.left <= left && this.top <= top - && this.right >= right && this.bottom >= bottom; - } - - /** - * Returns true iff the specified rectangle r is inside or equal to this - * rectangle. An empty rectangle never contains another rectangle. - * - * @param r The rectangle being tested for containment. - * @return true iff the specified rectangle r is inside or equal to this - * rectangle - */ - public boolean contains(Rect r) { - // check for empty first - return this.left < this.right && this.top < this.bottom - // now check for containment - && left <= r.left && top <= r.top - && right >= r.right && bottom >= r.bottom; - } - - /** - * If the rectangle specified by left,top,right,bottom intersects this - * rectangle, return true and set this rectangle to that intersection, - * otherwise return false and do not change this rectangle. No check is - * performed to see if either rectangle is empty. Note: To just test for - * intersection, use intersects() - * - * @param left The left side of the rectangle being intersected with this - * rectangle - * @param top The top of the rectangle being intersected with this rectangle - * @param right The right side of the rectangle being intersected with this - * rectangle. - * @param bottom The bottom of the rectangle being intersected with this - * rectangle. - * @return true if the specified rectangle and this rectangle intersect - * (and this rectangle is then set to that intersection) else - * return false and do not change this rectangle. - */ - public boolean intersect(int left, int top, int right, int bottom) { - if (this.left < right && left < this.right - && this.top < bottom && top < this.bottom) { - if (this.left < left) { - this.left = left; - } - if (this.top < top) { - this.top = top; - } - if (this.right > right) { - this.right = right; - } - if (this.bottom > bottom) { - this.bottom = bottom; - } - return true; - } - return false; - } - - /** - * If the specified rectangle intersects this rectangle, return true and set - * this rectangle to that intersection, otherwise return false and do not - * change this rectangle. No check is performed to see if either rectangle - * is empty. To just test for intersection, use intersects() - * - * @param r The rectangle being intersected with this rectangle. - * @return true if the specified rectangle and this rectangle intersect - * (and this rectangle is then set to that intersection) else - * return false and do not change this rectangle. - */ - public boolean intersect(Rect r) { - return intersect(r.left, r.top, r.right, r.bottom); - } - - /** - * If rectangles a and b intersect, return true and set this rectangle to - * that intersection, otherwise return false and do not change this - * rectangle. No check is performed to see if either rectangle is empty. - * To just test for intersection, use intersects() - * - * @param a The first rectangle being intersected with - * @param b The second rectangle being intersected with - * @return true iff the two specified rectangles intersect. If they do, set - * this rectangle to that intersection. If they do not, return - * false and do not change this rectangle. - */ - public boolean setIntersect(Rect a, Rect b) { - if (a.left < b.right && b.left < a.right - && a.top < b.bottom && b.top < a.bottom) { - left = Math.max(a.left, b.left); - top = Math.max(a.top, b.top); - right = Math.min(a.right, b.right); - bottom = Math.min(a.bottom, b.bottom); - return true; - } - return false; - } - - /** - * Returns true if this rectangle intersects the specified rectangle. - * In no event is this rectangle modified. No check is performed to see - * if either rectangle is empty. To record the intersection, use intersect() - * or setIntersect(). - * - * @param left The left side of the rectangle being tested for intersection - * @param top The top of the rectangle being tested for intersection - * @param right The right side of the rectangle being tested for - * intersection - * @param bottom The bottom of the rectangle being tested for intersection - * @return true iff the specified rectangle intersects this rectangle. In - * no event is this rectangle modified. - */ - public boolean intersects(int left, int top, int right, int bottom) { - return this.left < right && left < this.right - && this.top < bottom && top < this.bottom; - } - - /** - * Returns true iff the two specified rectangles intersect. In no event are - * either of the rectangles modified. To record the intersection, - * use intersect() or setIntersect(). - * - * @param a The first rectangle being tested for intersection - * @param b The second rectangle being tested for intersection - * @return true iff the two specified rectangles intersect. In no event are - * either of the rectangles modified. - */ - public static boolean intersects(Rect a, Rect b) { - return a.left < b.right && b.left < a.right - && a.top < b.bottom && b.top < a.bottom; - } - - /** - * Update this Rect to enclose itself and the specified rectangle. If the - * specified rectangle is empty, nothing is done. If this rectangle is empty - * it is set to the specified rectangle. - * - * @param left The left edge being unioned with this rectangle - * @param top The top edge being unioned with this rectangle - * @param right The right edge being unioned with this rectangle - * @param bottom The bottom edge being unioned with this rectangle - */ - public void union(int left, int top, int right, int bottom) { - if ((left < right) && (top < bottom)) { - if ((this.left < this.right) && (this.top < this.bottom)) { - if (this.left > left) - this.left = left; - if (this.top > top) - this.top = top; - if (this.right < right) - this.right = right; - if (this.bottom < bottom) - this.bottom = bottom; - } else { - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; - } - } - } - - /** - * Update this Rect to enclose itself and the specified rectangle. If the - * specified rectangle is empty, nothing is done. If this rectangle is empty - * it is set to the specified rectangle. - * - * @param r The rectangle being unioned with this rectangle - */ - public void union(Rect r) { - union(r.left, r.top, r.right, r.bottom); - } - - /** - * Update this Rect to enclose itself and the [x,y] coordinate. There is no - * check to see that this rectangle is non-empty. - * - * @param x The x coordinate of the point to add to the rectangle - * @param y The y coordinate of the point to add to the rectangle - */ - public void union(int x, int y) { - if (x < left) { - left = x; - } else if (x > right) { - right = x; - } - if (y < top) { - top = y; - } else if (y > bottom) { - bottom = y; - } - } - - /** - * Swap top/bottom or left/right if there are flipped (i.e. left > right - * and/or top > bottom). This can be called if - * the edges are computed separately, and may have crossed over each other. - * If the edges are already correct (i.e. left <= right and top <= bottom) - * then nothing is done. - */ - public void sort() { - if (left > right) { - int temp = left; - left = right; - right = temp; - } - if (top > bottom) { - int temp = top; - top = bottom; - bottom = temp; - } - } - - /** - * Parcelable interface methods - */ - public int describeContents() { - return 0; - } - - /** - * Write this rectangle to the specified parcel. To restore a rectangle from - * a parcel, use readFromParcel() - * @param out The parcel to write the rectangle's coordinates into - */ - public void writeToParcel(Parcel out, int flags) { - out.writeInt(left); - out.writeInt(top); - out.writeInt(right); - out.writeInt(bottom); - } - - public static final Parcelable.Creator- * The simplest way to create a frame-by-frame animation is to define the animation in an XML - * file, placed in the res/drawable/ folder, and set it as the background to a View object. Then, call - * {@link #run()} to start the animation. - *
- * An AnimationDrawable defined in XML consists of a single <animation-list>
element,
- * and a series of nested <item>
tags. Each item defines a frame of the animation.
- * See the example below.
- *
spin_animation.xml file in res/drawable/ folder:
- *<!-- Animation frames are wheel0.png -- wheel5.png files inside the - * res/drawable/ folder --> - * <animation-list android:id="selected" android:oneshot="false"> - * <item android:drawable="@drawable/wheel0" android:duration="50" /> - * <item android:drawable="@drawable/wheel1" android:duration="50" /> - * <item android:drawable="@drawable/wheel2" android:duration="50" /> - * <item android:drawable="@drawable/wheel3" android:duration="50" /> - * <item android:drawable="@drawable/wheel4" android:duration="50" /> - * <item android:drawable="@drawable/wheel5" android:duration="50" /> - * </animation-list>- * - *
Here is the code to load and play this animation.
- *- * // Load the ImageView that will host the animation and - * // set its background to our AnimationDrawable XML resource. - * ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image); - * img.setBackgroundResource(R.drawable.spin_animation); - * - * // Get the background, which has been compiled to an AnimationDrawable object. - * AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); - * - * // Start the animation (looped playback by default). - * frameAnimation.start() - *- * - * @attr ref android.R.styleable#AnimationDrawable_visible - * @attr ref android.R.styleable#AnimationDrawable_variablePadding - * @attr ref android.R.styleable#AnimationDrawable_oneshot - * @attr ref android.R.styleable#AnimationDrawableItem_duration - * @attr ref android.R.styleable#AnimationDrawableItem_drawable - */ -public class AnimationDrawable extends DrawableContainer implements Runnable { - private final AnimationState mAnimationState; - private int mCurFrame = -1; - private boolean mMutated; - - public AnimationDrawable() { - this(null); - } - - @Override - public boolean setVisible(boolean visible, boolean restart) { - boolean changed = super.setVisible(visible, restart); - if (visible) { - if (changed || restart) { - setFrame(0, true, true); - } - } else { - unscheduleSelf(this); - } - return changed; - } - - /** - *
Starts the animation, looping if necessary. This method has no effect - * if the animation is running.
- * - * @see #isRunning() - * @see #stop() - */ - public void start() { - if (!isRunning()) { - run(); - } - } - - /** - *Stops the animation. This method has no effect if the animation is - * not running.
- * - * @see #isRunning() - * @see #start() - */ - public void stop() { - if (isRunning()) { - unscheduleSelf(this); - } - } - - /** - *Indicates whether the animation is currently running or not.
- * - * @return true if the animation is running, false otherwise - */ - public boolean isRunning() { - return mCurFrame > -1; - } - - /** - *This method exists for implementation purpose only and should not be - * called directly. Invoke {@link #start()} instead.
- * - * @see #start() - */ - public void run() { - nextFrame(false); - } - - @Override - public void unscheduleSelf(Runnable what) { - mCurFrame = -1; - super.unscheduleSelf(what); - } - - /** - * @return The number of frames in the animation - */ - public int getNumberOfFrames() { - return mAnimationState.getChildCount(); - } - - /** - * @return The Drawable at the specified frame index - */ - public Drawable getFrame(int index) { - return mAnimationState.getChildren()[index]; - } - - /** - * @return The duration in milliseconds of the frame at the - * specified index - */ - public int getDuration(int i) { - return mAnimationState.mDurations[i]; - } - - /** - * @return True of the animation will play once, false otherwise - */ - public boolean isOneShot() { - return mAnimationState.mOneShot; - } - - /** - * Sets whether the animation should play once or repeat. - * - * @param oneShot Pass true if the animation should only play once - */ - public void setOneShot(boolean oneShot) { - mAnimationState.mOneShot = oneShot; - } - - /** - * Add a frame to the animation - * - * @param frame The frame to add - * @param duration How long in milliseconds the frame should appear - */ - public void addFrame(Drawable frame, int duration) { - mAnimationState.addFrame(frame, duration); - } - - private void nextFrame(boolean unschedule) { - int next = mCurFrame+1; - final int N = mAnimationState.getChildCount(); - if (next >= N) { - next = 0; - } - setFrame(next, unschedule, !mAnimationState.mOneShot || next < (N - 1)); - } - - private void setFrame(int frame, boolean unschedule, boolean animate) { - if (frame >= mAnimationState.getChildCount()) { - return; - } - mCurFrame = frame; - selectDrawable(frame); - if (unschedule) { - unscheduleSelf(this); - } - if (animate) { - scheduleSelf(this, SystemClock.uptimeMillis() + mAnimationState.mDurations[frame]); - } - } - - @Override - public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) - throws XmlPullParserException, IOException { - - TypedArray a = r.obtainAttributes(attrs, - com.android.internal.R.styleable.AnimationDrawable); - - super.inflateWithAttributes(r, parser, a, - com.android.internal.R.styleable.AnimationDrawable_visible); - - mAnimationState.setVariablePadding(a.getBoolean( - com.android.internal.R.styleable.AnimationDrawable_variablePadding, false)); - - mAnimationState.mOneShot = a.getBoolean( - com.android.internal.R.styleable.AnimationDrawable_oneshot, false); - - a.recycle(); - - int type; - - final int innerDepth = parser.getDepth()+1; - int depth; - while ((type=parser.next()) != XmlPullParser.END_DOCUMENT && - ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) { - if (type != XmlPullParser.START_TAG) { - continue; - } - - if (depth > innerDepth || !parser.getName().equals("item")) { - continue; - } - - a = r.obtainAttributes(attrs, com.android.internal.R.styleable.AnimationDrawableItem); - int duration = a.getInt( - com.android.internal.R.styleable.AnimationDrawableItem_duration, -1); - if (duration < 0) { - throw new XmlPullParserException( - parser.getPositionDescription() - + ":It can be defined in an XML file with the <bitmap>
element.
- * Also see the {@link android.graphics.Bitmap} class, which handles the management and - * transformation of raw bitmap graphics, and should be used when drawing to a - * {@link android.graphics.Canvas}. - *
- * - * @attr ref android.R.styleable#BitmapDrawable_src - * @attr ref android.R.styleable#BitmapDrawable_antialias - * @attr ref android.R.styleable#BitmapDrawable_filter - * @attr ref android.R.styleable#BitmapDrawable_dither - * @attr ref android.R.styleable#BitmapDrawable_gravity - * @attr ref android.R.styleable#BitmapDrawable_tileMode - */ -public class BitmapDrawable extends Drawable { - - private static final int DEFAULT_PAINT_FLAGS = Paint.FILTER_BITMAP_FLAG; - private BitmapState mBitmapState; - private Bitmap mBitmap; - private final Rect mDstRect = new Rect(); // Gravity.apply() sets this - - private boolean mApplyGravity; - private boolean mRebuildShader; - private int mBitmapWidth; - private int mBitmapHeight; - private boolean mMutated; - - public BitmapDrawable() { - mBitmapState = new BitmapState((Bitmap) null); - } - - public BitmapDrawable(Bitmap bitmap) { - this(new BitmapState(bitmap)); - } - - public BitmapDrawable(String filepath) { - this(new BitmapState(BitmapFactory.decodeFile(filepath))); - if (mBitmap == null) { - android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + filepath); - } - } - - public BitmapDrawable(java.io.InputStream is) { - this(new BitmapState(BitmapFactory.decodeStream(is))); - if (mBitmap == null) { - android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + is); - } - } - - public final Paint getPaint() { - return mBitmapState.mPaint; - } - - public final Bitmap getBitmap() { - return mBitmap; - } - - private void setBitmap(Bitmap bitmap) { - mBitmap = bitmap; - if (bitmap != null) { - mBitmapWidth = bitmap.getWidth(); - mBitmapHeight = bitmap.getHeight(); - } else { - mBitmapWidth = mBitmapHeight = -1; - } - } - - /** - * Set the density scale at which this drawable will be rendered. This - * method assumes the drawable will be rendered at the same density as the - * specified canvas. - * - * @param canvas The Canvas from which the density scale must be obtained. - * - * @see android.graphics.Bitmap#setDensityScale(float) - * @see android.graphics.Bitmap#getDensityScale() - * - * @hide pending API council approval - */ - public void setDensityScale(Canvas canvas) { - setDensityScale(canvas.getDensityScale()); - } - - /** - * Set the density scale at which this drawable will be rendered. - * - * @param metrics The DisplayMetrics indicating the density scale for this drawable. - * - * @see android.graphics.Bitmap#setDensityScale(float) - * @see android.graphics.Bitmap#getDensityScale() - * - * @hide pending API council approval - */ - public void setDensityScale(DisplayMetrics metrics) { - setDensityScale(metrics.density); - } - - /** - * Set the density scale at which this drawable will be rendered. - * - * @param density The density scale for this drawable. - * - * @see android.graphics.Bitmap#setDensityScale(float) - * @see android.graphics.Bitmap#getDensityScale() - * - * @hide pending API council approval - */ - public void setDensityScale(float density) { - density = (density == Bitmap.DENSITY_SCALE_UNKNOWN ? 1.0f : density); - mBitmapState.mTargetDensityScale = density; - } - - /** Get the gravity used to position/stretch the bitmap within its bounds. - See android.view.Gravity - * @return the gravity applied to the bitmap - */ - public int getGravity() { - return mBitmapState.mGravity; - } - - /** Set the gravity used to position/stretch the bitmap within its bounds. - See android.view.Gravity - * @param gravity the gravity - */ - public void setGravity(int gravity) { - mBitmapState.mGravity = gravity; - mApplyGravity = true; - } - - public void setAntiAlias(boolean aa) { - mBitmapState.mPaint.setAntiAlias(aa); - } - - @Override - public void setFilterBitmap(boolean filter) { - mBitmapState.mPaint.setFilterBitmap(filter); - } - - @Override - public void setDither(boolean dither) { - mBitmapState.mPaint.setDither(dither); - } - - public Shader.TileMode getTileModeX() { - return mBitmapState.mTileModeX; - } - - public Shader.TileMode getTileModeY() { - return mBitmapState.mTileModeY; - } - - public void setTileModeX(Shader.TileMode mode) { - setTileModeXY(mode, mBitmapState.mTileModeY); - } - - public final void setTileModeY(Shader.TileMode mode) { - setTileModeXY(mBitmapState.mTileModeX, mode); - } - - public void setTileModeXY(Shader.TileMode xmode, Shader.TileMode ymode) { - final BitmapState state = mBitmapState; - if (state.mTileModeX != xmode || state.mTileModeY != ymode) { - state.mTileModeX = xmode; - state.mTileModeY = ymode; - mRebuildShader = true; - } - } - - @Override - public int getChangingConfigurations() { - return super.getChangingConfigurations() | mBitmapState.mChangingConfigurations; - } - - @Override - protected void onBoundsChange(Rect bounds) { - super.onBoundsChange(bounds); - mApplyGravity = true; - } - - @Override - public void draw(Canvas canvas) { - Bitmap bitmap = mBitmap; - if (bitmap != null) { - final BitmapState state = mBitmapState; - if (mRebuildShader) { - Shader.TileMode tmx = state.mTileModeX; - Shader.TileMode tmy = state.mTileModeY; - - if (tmx == null && tmy == null) { - state.mPaint.setShader(null); - } else { - Shader s = new BitmapShader(bitmap, - tmx == null ? Shader.TileMode.CLAMP : tmx, - tmy == null ? Shader.TileMode.CLAMP : tmy); - state.mPaint.setShader(s); - } - mRebuildShader = false; - copyBounds(mDstRect); - } - - Shader shader = state.mPaint.getShader(); - if (shader == null) { - if (mApplyGravity) { - Gravity.apply(state.mGravity, mBitmapWidth, mBitmapHeight, - getBounds(), mDstRect); - mApplyGravity = false; - } - canvas.drawBitmap(bitmap, null, mDstRect, state.mPaint); - } else { - if (mApplyGravity) { - mDstRect.set(getBounds()); - mApplyGravity = false; - } - canvas.drawRect(mDstRect, state.mPaint); - } - } - } - - @Override - public void setAlpha(int alpha) { - mBitmapState.mPaint.setAlpha(alpha); - } - - @Override - public void setColorFilter(ColorFilter cf) { - mBitmapState.mPaint.setColorFilter(cf); - } - - /** - * A mutable BitmapDrawable still shares its Bitmap with any other Drawable - * that comes from the same resource. - * - * @return This drawable. - */ - @Override - public Drawable mutate() { - if (!mMutated && super.mutate() == this) { - mBitmapState = new BitmapState(mBitmapState); - mMutated = true; - } - return this; - } - - @Override - public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) - throws XmlPullParserException, IOException { - super.inflate(r, parser, attrs); - - TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.BitmapDrawable); - - final int id = a.getResourceId(com.android.internal.R.styleable.BitmapDrawable_src, 0); - if (id == 0) { - throw new XmlPullParserException(parser.getPositionDescription() + - ":It can be defined in an XML file with the <clip>
element.
It can be defined in an XML file with the <color>
element.
In addition to simple drawing, Drawable provides a number of generic - * mechanisms for its client to interact with what is being drawn: - * - *
For information and examples of creating drawable resources (XML or bitmap files that - * can be loaded in code), see Resources - * and Internationalization. - */ -public abstract class Drawable { - - private int[] mStateSet = StateSet.WILD_CARD; - private int mLevel = 0; - private int mChangingConfigurations = 0; - private Rect mBounds = new Rect(); - /*package*/ Callback mCallback = null; - private boolean mVisible = true; - - /** - * Draw in its bounds (set via setBounds) respecting optional effects such - * as alpha (set via setAlpha) and color filter (set via setColorFilter). - * - * @param canvas The canvas to draw into - */ - public abstract void draw(Canvas canvas); - - /** - * Specify a bounding rectangle for the Drawable. This is where the drawable - * will draw when its draw() method is called. - */ - public void setBounds(int left, int top, int right, int bottom) { - Rect oldBounds = mBounds; - - if (oldBounds.left != left || oldBounds.top != top || - oldBounds.right != right || oldBounds.bottom != bottom) { - mBounds.set(left, top, right, bottom); - onBoundsChange(mBounds); - } - } - - /** - * Specify a bounding rectangle for the Drawable. This is where the drawable - * will draw when its draw() method is called. - */ - public void setBounds(Rect bounds) { - setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom); - } - - /** - * Return a copy of the drawable's bounds in the specified Rect (allocated - * by the caller). The bounds specify where this will draw when its draw() - * method is called. - * - * @param bounds Rect to receive the drawable's bounds (allocated by the - * caller). - */ - public final void copyBounds(Rect bounds) { - bounds.set(mBounds); - } - - /** - * Return a copy of the drawable's bounds in a new Rect. This returns the - * same values as getBounds(), but the returned object is guaranteed to not - * be changed later by the drawable (i.e. it retains no reference to this - * rect). If the caller already has a Rect allocated, call copyBounds(rect) - * - * @return A copy of the drawable's bounds - */ - public final Rect copyBounds() { - return new Rect(mBounds); - } - - /** - * Return the drawable's bounds Rect. Note: for efficiency, the returned - * object may be the same object stored in the drawable (though this is not - * guaranteed), so if a persistent copy of the bounds is needed, call - * copyBounds(rect) instead. - * - * @return The bounds of the drawable (which may change later, so caller - * beware). - */ - public final Rect getBounds() { - return mBounds; - } - - /** - * Set a mask of the configuration parameters for which this drawable - * may change, requiring that it be re-created. - * - * @param configs A mask of the changing configuration parameters, as - * defined by {@link android.content.res.Configuration}. - * - * @see android.content.res.Configuration - */ - public void setChangingConfigurations(int configs) { - mChangingConfigurations = configs; - } - - /** - * Return a mask of the configuration parameters for which this drawable - * mau change, requiring that it be re-created. The default implementation - * returns whatever was provided through - * {@link #setChangingConfigurations(int)} or 0 by default. Subclasses - * may extend this to or in the changing configurations of any other - * drawables they hold. - * - * @return Returns a mask of the changing configuration parameters, as - * defined by {@link android.content.res.Configuration}. - * - * @see android.content.res.Configuration - */ - public int getChangingConfigurations() { - return mChangingConfigurations; - } - - /** - * Set to true to have the drawable dither its colors when drawn to a device - * with fewer than 8-bits per color component. This can improve the look on - * those devices, but can also slow down the drawing a little. - */ - public void setDither(boolean dither) {} - - /** - * Set to true to have the drawable filter its bitmap when scaled or rotated - * (for drawables that use bitmaps). If the drawable does not use bitmaps, - * this call is ignored. This can improve the look when scaled or rotated, - * but also slows down the drawing. - */ - public void setFilterBitmap(boolean filter) {} - - /** - * Implement this interface if you want to create an animated drawable that - * extends {@link android.graphics.drawable.Drawable Drawable}. - * Upon retrieving a drawable, use - * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)} - * to supply your implementation of the interface to the drawable; it uses - * this interface to schedule and execute animation changes. - */ - public static interface Callback { - /** - * Called when the drawable needs to be redrawn. A view at this point - * should invalidate itself (or at least the part of itself where the - * drawable appears). - * - * @param who The drawable that is requesting the update. - */ - public void invalidateDrawable(Drawable who); - - /** - * A Drawable can call this to schedule the next frame of its - * animation. An implementation can generally simply call - * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with - * the parameters (what, who, when) to perform the - * scheduling. - * - * @param who The drawable being scheduled. - * @param what The action to execute. - * @param when The time (in milliseconds) to run. The timebase is - * {@link android.os.SystemClock#uptimeMillis} - */ - public void scheduleDrawable(Drawable who, Runnable what, long when); - - /** - * A Drawable can call this to unschedule an action previously - * scheduled with {@link #scheduleDrawable}. An implementation can - * generally simply call - * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with - * the parameters (what, who) to unschedule the drawable. - * - * @param who The drawable being unscheduled. - * @param what The action being unscheduled. - */ - public void unscheduleDrawable(Drawable who, Runnable what); - } - - /** - * Bind a {@link Callback} object to this Drawable. Required for clients - * that want to support animated drawables. - * - * @param cb The client's Callback implementation. - */ - public final void setCallback(Callback cb) { - mCallback = cb; - } - - /** - * Use the current {@link Callback} implementation to have this Drawable - * redrawn. Does nothing if there is no Callback attached to the - * Drawable. - * - * @see Callback#invalidateDrawable - */ - public void invalidateSelf() - { - if (mCallback != null) { - mCallback.invalidateDrawable(this); - } - } - - /** - * Use the current {@link Callback} implementation to have this Drawable - * scheduled. Does nothing if there is no Callback attached to the - * Drawable. - * - * @param what The action being scheduled. - * @param when The time (in milliseconds) to run. - * - * @see Callback#scheduleDrawable - */ - public void scheduleSelf(Runnable what, long when) - { - if (mCallback != null) { - mCallback.scheduleDrawable(this, what, when); - } - } - - /** - * Use the current {@link Callback} implementation to have this Drawable - * unscheduled. Does nothing if there is no Callback attached to the - * Drawable. - * - * @param what The runnable that you no longer want called. - * - * @see Callback#unscheduleDrawable - */ - public void unscheduleSelf(Runnable what) - { - if (mCallback != null) { - mCallback.unscheduleDrawable(this, what); - } - } - - /** - * Specify an alpha value for the drawable. 0 means fully transparent, and - * 255 means fully opaque. - */ - public abstract void setAlpha(int alpha); - - /** - * Specify an optional colorFilter for the drawable. Pass null to remove - * any filters. - */ - public abstract void setColorFilter(ColorFilter cf); - - /** - * Specify a color and porterduff mode to be the colorfilter for this - * drawable. - */ - public void setColorFilter(int color, PorterDuff.Mode mode) { - setColorFilter(new PorterDuffColorFilter(color, mode)); - } - - public void clearColorFilter() { - setColorFilter(null); - } - - /** - * Indicates whether this view will change its appearance based on state. - * Clients can use this to determine whether it is necessary to calculate - * their state and call setState. - * - * @return True if this view changes its appearance based on state, false - * otherwise. - * - * @see #setState(int[]) - */ - public boolean isStateful() { - return false; - } - - /** - * Specify a set of states for the drawable. These are use-case specific, - * so see the relevant documentation. As an example, the background for - * widgets like Button understand the following states: - * [{@link android.R.attr#state_focused}, - * {@link android.R.attr#state_pressed}]. - * - *
If the new state you are supplying causes the appearance of the - * Drawable to change, then it is responsible for calling - * {@link #invalidateSelf} in order to have itself redrawn, and - * true will be returned from this function. - * - *
Note: The Drawable holds a reference on to stateSet - * until a new state array is given to it, so you must not modify this - * array during that time.
- * - * @param stateSet The new set of states to be displayed. - * - * @return Returns true if this change in state has caused the appearance - * of the Drawable to change (hence requiring an invalidate), otherwise - * returns false. - */ - public boolean setState(final int[] stateSet) { - if (!Arrays.equals(mStateSet, stateSet)) { - mStateSet = stateSet; - return onStateChange(stateSet); - } - return false; - } - - /** - * Describes the current state, as a union of primitve states, such as - * {@link android.R.attr#state_focused}, - * {@link android.R.attr#state_selected}, etc. - * Some drawables may modify their imagery based on the selected state. - * @return An array of resource Ids describing the current state. - */ - public int[] getState() { - return mStateSet; - } - - /** - * @return The current drawable that will be used by this drawable. For simple drawables, this - * is just the drawable itself. For drawables that change state like - * {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable - * currently in use. - */ - public Drawable getCurrent() { - return this; - } - - /** - * Specify the level for the drawable. This allows a drawable to vary its - * imagery based on a continuous controller, for example to show progress - * or volume level. - * - *If the new level you are supplying causes the appearance of the - * Drawable to change, then it is responsible for calling - * {@link #invalidateSelf} in order to have itself redrawn, and - * true will be returned from this function. - * - * @param level The new level, from 0 (minimum) to 10000 (maximum). - * - * @return Returns true if this change in level has caused the appearance - * of the Drawable to change (hence requiring an invalidate), otherwise - * returns false. - */ - public final boolean setLevel(int level) { - if (mLevel != level) { - mLevel = level; - return onLevelChange(level); - } - return false; - } - - /** - * Retrieve the current level. - * - * @return int Current level, from 0 (minimum) to 10000 (maximum). - */ - public final int getLevel() { - return mLevel; - } - - /** - * Set whether this Drawable is visible. This generally does not impact - * the Drawable's behavior, but is a hint that can be used by some - * Drawables, for example, to decide whether run animations. - * - * @param visible Set to true if visible, false if not. - * @param restart You can supply true here to force the drawable to behave - * as if it has just become visible, even if it had last - * been set visible. Used for example to force animations - * to restart. - * - * @return boolean Returns true if the new visibility is different than - * its previous state. - */ - public boolean setVisible(boolean visible, boolean restart) { - boolean changed = mVisible != visible; - mVisible = visible; - return changed; - } - - public final boolean isVisible() { - return mVisible; - } - - /** - * Return the opacity/transparency of this Drawable. The returned value is - * one of the abstract format constants in - * {@link android.graphics.PixelFormat}: - * {@link android.graphics.PixelFormat#UNKNOWN}, - * {@link android.graphics.PixelFormat#TRANSLUCENT}, - * {@link android.graphics.PixelFormat#TRANSPARENT}, or - * {@link android.graphics.PixelFormat#OPAQUE}. - * - *
Generally a Drawable should be as conservative as possible with the - * value it returns. For example, if it contains multiple child drawables - * and only shows one of them at a time, if only one of the children is - * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be - * returned. You can use the method {@link #resolveOpacity} to perform a - * standard reduction of two opacities to the appropriate single output. - * - *
Note that the returned value does not take into account a - * custom alpha or color filter that has been applied by the client through - * the {@link #setAlpha} or {@link #setColorFilter} methods. - * - * @return int The opacity class of the Drawable. - * - * @see android.graphics.PixelFormat - */ - public abstract int getOpacity(); - - /** - * Return the appropriate opacity value for two source opacities. If - * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT, - * that is returned; else, if either is TRANSPARENT, that is returned; - * else, OPAQUE is returned. - * - *
This is to help in implementing {@link #getOpacity}.
- *
- * @param op1 One opacity value.
- * @param op2 Another opacity value.
- *
- * @return int The combined opacity value.
- *
- * @see #getOpacity
- */
- public static int resolveOpacity(int op1, int op2) {
- if (op1 == op2) {
- return op1;
- }
- if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
- return PixelFormat.UNKNOWN;
- }
- if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
- return PixelFormat.TRANSLUCENT;
- }
- if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
- return PixelFormat.TRANSPARENT;
- }
- return PixelFormat.OPAQUE;
- }
-
- /**
- * Returns a Region representing the part of the Drawable that is completely
- * transparent. This can be used to perform drawing operations, identifying
- * which parts of the target will not change when rendering the Drawable.
- * The default implementation returns null, indicating no transparent
- * region; subclasses can optionally override this to return an actual
- * Region if they want to supply this optimization information, but it is
- * not required that they do so.
- *
- * @return Returns null if the Drawables has no transparent region to
- * report, else a Region holding the parts of the Drawable's bounds that
- * are transparent.
- */
- public Region getTransparentRegion() {
- return null;
- }
-
- /**
- * Override this in your subclass to change appearance if you recognize the
- * specified state.
- *
- * @return Returns true if the state change has caused the appearance of
- * the Drawable to change (that is, it needs to be drawn), else false
- * if it looks the same and there is no need to redraw it since its
- * last state.
- */
- protected boolean onStateChange(int[] state) { return false; }
- /** Override this in your subclass to change appearance if you vary based
- * on level.
- * @return Returns true if the level change has caused the appearance of
- * the Drawable to change (that is, it needs to be drawn), else false
- * if it looks the same and there is no need to redraw it since its
- * last level.
- */
- protected boolean onLevelChange(int level) { return false; }
- /**
- * Override this in your subclass to change appearance if you recognize the
- * specified state.
- */
- protected void onBoundsChange(Rect bounds) {}
-
- /**
- * Return the intrinsic width of the underlying drawable object. Returns
- * -1 if it has no intrinsic width, such as with a solid color.
- */
- public int getIntrinsicWidth() {
- return -1;
- }
-
- /**
- * Return the intrinsic height of the underlying drawable object. Returns
- * -1 if it has no intrinsic height, such as with a solid color.
- */
- public int getIntrinsicHeight() {
- return -1;
- }
-
- /**
- * Returns the minimum width suggested by this Drawable. If a View uses this
- * Drawable as a background, it is suggested that the View use at least this
- * value for its width. (There will be some scenarios where this will not be
- * possible.) This value should INCLUDE any padding.
- *
- * @return The minimum width suggested by this Drawable. If this Drawable
- * doesn't have a suggested minimum width, 0 is returned.
- */
- public int getMinimumWidth() {
- final int intrinsicWidth = getIntrinsicWidth();
- return intrinsicWidth > 0 ? intrinsicWidth : 0;
- }
-
- /**
- * Returns the minimum height suggested by this Drawable. If a View uses this
- * Drawable as a background, it is suggested that the View use at least this
- * value for its height. (There will be some scenarios where this will not be
- * possible.) This value should INCLUDE any padding.
- *
- * @return The minimum height suggested by this Drawable. If this Drawable
- * doesn't have a suggested minimum height, 0 is returned.
- */
- public int getMinimumHeight() {
- final int intrinsicHeight = getIntrinsicHeight();
- return intrinsicHeight > 0 ? intrinsicHeight : 0;
- }
-
- /**
- * Return in padding the insets suggested by this Drawable for placing
- * content inside the drawable's bounds. Positive values move toward the
- * center of the Drawable (set Rect.inset). Returns true if this drawable
- * actually has a padding, else false. When false is returned, the padding
- * is always set to 0.
- */
- public boolean getPadding(Rect padding) {
- padding.set(0, 0, 0, 0);
- return false;
- }
-
- /**
- * Make this drawable mutable. This operation cannot be reversed. A mutable
- * drawable is guaranteed to not share its state with any other drawable.
- * This is especially useful when you need to modify properties of drawables
- * loaded from resources. By default, all drawables instances loaded from
- * the same resource share a common state; if you modify the state of one
- * instance, all the other instances will receive the same modification.
- *
- * Calling this method on a mutable Drawable will have no effect.
- *
- * @return This drawable.
- */
- public Drawable mutate() {
- return this;
- }
-
- /**
- * Create a drawable from an inputstream
- */
- public static Drawable createFromStream(InputStream is, String srcName) {
- return createFromResourceStream(null, null, is, srcName);
- }
-
- /**
- * Create a drawable from an inputstream
- *
- * @hide pending API council approval
- */
- public static Drawable createFromResourceStream(Resources res, TypedValue value,
- InputStream is, String srcName) {
-
- if (is == null) {
- return null;
- }
-
- /* ugh. The decodeStream contract is that we have already allocated
- the pad rect, but if the bitmap does not had a ninepatch chunk,
- then the pad will be ignored. If we could change this to lazily
- alloc/assign the rect, we could avoid the GC churn of making new
- Rects only to drop them on the floor.
- */
- Rect pad = new Rect();
- Bitmap bm = BitmapFactory.decodeStream(res, value, is, pad, null);
- if (bm != null) {
- byte[] np = bm.getNinePatchChunk();
- if (np == null || !NinePatch.isNinePatchChunk(np)) {
- np = null;
- pad = null;
- }
- return drawableFromBitmap(res, bm, np, pad, srcName);
- }
- return null;
- }
-
- /**
- * Create a drawable from an XML document. For more information on how to
- * create resources in XML, see
- * Resources and
- * Internationalization.
- */
- public static Drawable createFromXml(Resources r, XmlPullParser parser)
- throws XmlPullParserException, IOException {
- AttributeSet attrs = Xml.asAttributeSet(parser);
-
- int type;
- while ((type=parser.next()) != XmlPullParser.START_TAG &&
- type != XmlPullParser.END_DOCUMENT) {
- // Empty loop
- }
-
- if (type != XmlPullParser.START_TAG) {
- throw new XmlPullParserException("No start tag found");
- }
-
- Drawable drawable = createFromXmlInner(r, parser, attrs);
-
- if (drawable == null) {
- throw new RuntimeException("Unknown initial tag: " + parser.getName());
- }
-
- return drawable;
- }
-
- /**
- * Create from inside an XML document. Called on a parser positioned at
- * a tag in an XML document, tries to create a Drawable from that tag.
- * Returns null if the tag is not a valid drawable.
- */
- public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
- throws XmlPullParserException, IOException {
- Drawable drawable;
-
- final String name = parser.getName();
-
- if (name.equals("selector")) {
- drawable = new StateListDrawable();
- } else if (name.equals("level-list")) {
- drawable = new LevelListDrawable();
- } else if (name.equals("layer-list")) {
- drawable = new LayerDrawable();
- } else if (name.equals("transition")) {
- drawable = new TransitionDrawable();
- } else if (name.equals("color")) {
- drawable = new ColorDrawable();
- } else if (name.equals("shape")) {
- drawable = new GradientDrawable();
- } else if (name.equals("scale")) {
- drawable = new ScaleDrawable();
- } else if (name.equals("clip")) {
- drawable = new ClipDrawable();
- } else if (name.equals("rotate")) {
- drawable = new RotateDrawable();
- } else if (name.equals("animation-list")) {
- drawable = new AnimationDrawable();
- } else if (name.equals("inset")) {
- drawable = new InsetDrawable();
- } else if (name.equals("bitmap")) {
- drawable = new BitmapDrawable();
- if (r != null) {
- ((BitmapDrawable) drawable).setDensityScale(r.getDisplayMetrics());
- }
- } else {
- throw new XmlPullParserException(parser.getPositionDescription() +
- ": invalid drawable tag " + name);
- }
-
- drawable.inflate(r, parser, attrs);
- return drawable;
- }
-
-
- /**
- * Create a drawable from file path name.
- */
- public static Drawable createFromPath(String pathName) {
- if (pathName == null) {
- return null;
- }
-
- Bitmap bm = BitmapFactory.decodeFile(pathName);
- if (bm != null) {
- return drawableFromBitmap(null, bm, null, null, pathName);
- }
-
- return null;
- }
-
- public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
- throws XmlPullParserException, IOException {
-
- TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable);
- inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible);
- a.recycle();
- }
-
- void inflateWithAttributes(Resources r, XmlPullParser parser,
- TypedArray attrs, int visibleAttr)
- throws XmlPullParserException, IOException {
-
- mVisible = attrs.getBoolean(visibleAttr, mVisible);
- }
-
- public static abstract class ConstantState {
- public abstract Drawable newDrawable();
- public abstract int getChangingConfigurations();
- }
-
- public ConstantState getConstantState() {
- return null;
- }
-
- private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
- Rect pad, String srcName) {
-
- if (np != null) {
- return new NinePatchDrawable(bm, np, pad, srcName);
- }
-
- final BitmapDrawable drawable = new BitmapDrawable(bm);
- if (res != null) {
- drawable.setDensityScale(res.getDisplayMetrics());
- }
-
- return drawable;
- }
-}
-
diff --git a/graphics/java/android/graphics/drawable/DrawableContainer.java b/graphics/java/android/graphics/drawable/DrawableContainer.java
deleted file mode 100644
index 29f2a00..0000000
--- a/graphics/java/android/graphics/drawable/DrawableContainer.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.graphics.drawable;
-
-import android.graphics.*;
-
-public class DrawableContainer extends Drawable implements Drawable.Callback {
-
- private DrawableContainerState mDrawableContainerState;
- private Drawable mCurrDrawable;
- private int mAlpha = 0xFF;
- private ColorFilter mColorFilter;
- private boolean mDither;
-
- private int mCurIndex = -1;
- private boolean mMutated;
-
- // overrides from Drawable
-
- @Override
- public void draw(Canvas canvas) {
- if (mCurrDrawable != null) {
- mCurrDrawable.draw(canvas);
- }
- }
-
- @Override
- public int getChangingConfigurations() {
- return super.getChangingConfigurations()
- | mDrawableContainerState.mChangingConfigurations
- | mDrawableContainerState.mChildrenChangingConfigurations;
- }
-
- @Override
- public boolean getPadding(Rect padding) {
- final Rect r = mDrawableContainerState.getConstantPadding();
- if (r != null) {
- padding.set(r);
- return true;
- }
- if (mCurrDrawable != null) {
- return mCurrDrawable.getPadding(padding);
- } else {
- return super.getPadding(padding);
- }
- }
-
- @Override
- public void setAlpha(int alpha) {
- if (mAlpha != alpha) {
- mAlpha = alpha;
- if (mCurrDrawable != null) {
- mCurrDrawable.setAlpha(alpha);
- }
- }
- }
-
- @Override
- public void setDither(boolean dither) {
- if (mDither != dither) {
- mDither = dither;
- if (mCurrDrawable != null) {
- mCurrDrawable.setDither(mDither);
- }
- }
- }
-
- @Override
- public void setColorFilter(ColorFilter cf) {
- if (mColorFilter != cf) {
- mColorFilter = cf;
- if (mCurrDrawable != null) {
- mCurrDrawable.setColorFilter(cf);
- }
- }
- }
-
- @Override
- protected void onBoundsChange(Rect bounds) {
- if (mCurrDrawable != null) {
- mCurrDrawable.setBounds(bounds);
- }
- }
-
- @Override
- public boolean isStateful() {
- return mDrawableContainerState.isStateful();
- }
-
- @Override
- protected boolean onStateChange(int[] state) {
- if (mCurrDrawable != null) {
- return mCurrDrawable.setState(state);
- }
- return false;
- }
-
- @Override
- protected boolean onLevelChange(int level) {
- if (mCurrDrawable != null) {
- return mCurrDrawable.setLevel(level);
- }
- return false;
- }
-
- @Override
- public int getIntrinsicWidth() {
- if (mDrawableContainerState.isConstantSize()) {
- return mDrawableContainerState.getConstantWidth();
- }
- return mCurrDrawable != null ? mCurrDrawable.getIntrinsicWidth() : -1;
- }
-
- @Override
- public int getIntrinsicHeight() {
- if (mDrawableContainerState.isConstantSize()) {
- return mDrawableContainerState.getConstantHeight();
- }
- return mCurrDrawable != null ? mCurrDrawable.getIntrinsicHeight() : -1;
- }
-
- @Override
- public int getMinimumWidth() {
- if (mDrawableContainerState.isConstantSize()) {
- return mDrawableContainerState.getConstantMinimumWidth();
- }
- return mCurrDrawable != null ? mCurrDrawable.getMinimumWidth() : 0;
- }
-
- @Override
- public int getMinimumHeight() {
- if (mDrawableContainerState.isConstantSize()) {
- return mDrawableContainerState.getConstantMinimumHeight();
- }
- return mCurrDrawable != null ? mCurrDrawable.getMinimumHeight() : 0;
- }
-
- public void invalidateDrawable(Drawable who)
- {
- if (who == mCurrDrawable && mCallback != null) {
- mCallback.invalidateDrawable(this);
- }
- }
-
- public void scheduleDrawable(Drawable who, Runnable what, long when)
- {
- if (who == mCurrDrawable && mCallback != null) {
- mCallback.scheduleDrawable(this, what, when);
- }
- }
-
- public void unscheduleDrawable(Drawable who, Runnable what)
- {
- if (who == mCurrDrawable && mCallback != null) {
- mCallback.unscheduleDrawable(this, what);
- }
- }
-
- @Override
- public boolean setVisible(boolean visible, boolean restart) {
- boolean changed = super.setVisible(visible, restart);
- if (mCurrDrawable != null) {
- mCurrDrawable.setVisible(visible, restart);
- }
- return changed;
- }
-
- @Override
- public int getOpacity() {
- return mDrawableContainerState.getOpacity();
- }
-
- public boolean selectDrawable(int idx)
- {
- if (idx == mCurIndex) {
- return false;
- }
- if (idx >= 0 && idx < mDrawableContainerState.mNumChildren) {
- Drawable d = mDrawableContainerState.mDrawables[idx];
- if (mCurrDrawable != null) {
- mCurrDrawable.setVisible(false, false);
- }
- mCurrDrawable = d;
- mCurIndex = idx;
- if (d != null) {
- d.setVisible(isVisible(), true);
- d.setAlpha(mAlpha);
- d.setDither(mDither);
- d.setColorFilter(mColorFilter);
- d.setState(getState());
- d.setLevel(getLevel());
- d.setBounds(getBounds());
- }
- } else {
- if (mCurrDrawable != null) {
- mCurrDrawable.setVisible(false, false);
- }
- mCurrDrawable = null;
- mCurIndex = -1;
- }
- invalidateSelf();
- return true;
- }
-
- @Override
- public Drawable getCurrent() {
- return mCurrDrawable;
- }
-
- @Override
- public ConstantState getConstantState() {
- if (mDrawableContainerState.canConstantState()) {
- mDrawableContainerState.mChangingConfigurations = super.getChangingConfigurations();
- return mDrawableContainerState;
- }
- return null;
- }
-
- @Override
- public Drawable mutate() {
- if (!mMutated && super.mutate() == this) {
- for (Drawable child : mDrawableContainerState.mDrawables) {
- child.mutate();
- }
- mMutated = true;
- }
- return this;
- }
-
- public abstract static class DrawableContainerState extends ConstantState {
- final DrawableContainer mOwner;
-
- int mChangingConfigurations;
- int mChildrenChangingConfigurations;
-
- Drawable[] mDrawables;
- int mNumChildren;
-
- boolean mVariablePadding = false;
- Rect mConstantPadding = null;
-
- boolean mConstantSize = false;
- boolean mComputedConstantSize = false;
- int mConstantWidth;
- int mConstantHeight;
- int mConstantMinimumWidth;
- int mConstantMinimumHeight;
-
- boolean mHaveOpacity = false;
- int mOpacity;
-
- boolean mHaveStateful = false;
- boolean mStateful;
-
- boolean mCheckedConstantState;
- boolean mCanConstantState;
-
- DrawableContainerState(DrawableContainerState orig, DrawableContainer owner) {
- mOwner = owner;
-
- if (orig != null) {
- mChangingConfigurations = orig.mChangingConfigurations;
- mChildrenChangingConfigurations = orig.mChildrenChangingConfigurations;
-
- final Drawable[] origDr = orig.mDrawables;
-
- mDrawables = new Drawable[origDr.length];
- mNumChildren = orig.mNumChildren;
-
- final int N = mNumChildren;
- for (int i=0; i<shape>
element.
It can be defined in an XML file with the <inset>
element.
- * It can be defined in an XML file with the <layer-list>
element.
- * Each Drawable in the layer is defined in a nested <item>
.
- *
<level-list>
element.
- * Each Drawable level is defined in a nested <item>
- *
- *
- * @attr ref android.R.styleable#LevelListDrawableItem_minLevel
- * @attr ref android.R.styleable#LevelListDrawableItem_maxLevel
- * @attr ref android.R.styleable#LevelListDrawableItem_drawable
- */
-public class LevelListDrawable extends DrawableContainer {
- private final LevelListState mLevelListState;
- private boolean mMutated;
-
- public LevelListDrawable() {
- this(null);
- }
-
- public void addLevel(int low, int high, Drawable drawable) {
- if (drawable != null) {
- mLevelListState.addLevel(low, high, drawable);
- // in case the new state matches our current state...
- onLevelChange(getLevel());
- }
- }
-
- // overrides from Drawable
-
- @Override
- protected boolean onLevelChange(int level) {
- int idx = mLevelListState.indexOfLevel(level);
- if (selectDrawable(idx)) {
- return true;
- }
- return super.onLevelChange(level);
- }
-
- @Override
- public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
- throws XmlPullParserException, IOException {
-
- super.inflate(r, parser, attrs);
-
- int type;
-
- int low = 0;
-
- final int innerDepth = parser.getDepth() + 1;
- int depth;
- while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
- && ((depth = parser.getDepth()) >= innerDepth
- || type != XmlPullParser.END_TAG)) {
- if (type != XmlPullParser.START_TAG) {
- continue;
- }
-
- if (depth > innerDepth || !parser.getName().equals("item")) {
- continue;
- }
-
- TypedArray a = r.obtainAttributes(attrs,
- com.android.internal.R.styleable.LevelListDrawableItem);
-
- low = a.getInt(
- com.android.internal.R.styleable.LevelListDrawableItem_minLevel, 0);
- int high = a.getInt(
- com.android.internal.R.styleable.LevelListDrawableItem_maxLevel, 0);
- int drawableRes = a.getResourceId(
- com.android.internal.R.styleable.LevelListDrawableItem_drawable, 0);
-
- a.recycle();
-
- if (high < 0) {
- throw new XmlPullParserException(parser.getPositionDescription()
- + ": A Drawable that can rotate another Drawable based on the current level - * value. The start and end angles of rotation can be controlled to map any - * circular arc to the level values range.
- * - *It can be defined in an XML file with the <rotate>
element.
Create a new rotating drawable with an empty state.
- */ - public RotateDrawable() { - this(null); - } - - /** - *Create a new rotating drawable with the specified state. A copy of - * this state is used as the internal state for the newly created - * drawable.
- * - * @param rotateState the state for this drawable - */ - private RotateDrawable(RotateState rotateState) { - mState = new RotateState(rotateState, this); - } - - public void draw(Canvas canvas) { - int saveCount = canvas.save(); - - Rect bounds = mState.mDrawable.getBounds(); - - int w = bounds.right - bounds.left; - int h = bounds.bottom - bounds.top; - - final RotateState st = mState; - - float px = st.mPivotXRel ? (w * st.mPivotX) : st.mPivotX; - float py = st.mPivotYRel ? (h * st.mPivotY) : st.mPivotY; - - canvas.rotate(st.mCurrentDegrees, px, py); - - st.mDrawable.draw(canvas); - - canvas.restoreToCount(saveCount); - } - - /** - * Returns the drawable rotated by this RotateDrawable. - */ - public Drawable getDrawable() { - return mState.mDrawable; - } - - @Override - public int getChangingConfigurations() { - return super.getChangingConfigurations() - | mState.mChangingConfigurations - | mState.mDrawable.getChangingConfigurations(); - } - - public void setAlpha(int alpha) { - mState.mDrawable.setAlpha(alpha); - } - - public void setColorFilter(ColorFilter cf) { - mState.mDrawable.setColorFilter(cf); - } - - public int getOpacity() { - return mState.mDrawable.getOpacity(); - } - - public void invalidateDrawable(Drawable who) { - if (mCallback != null) { - mCallback.invalidateDrawable(this); - } - } - - public void scheduleDrawable(Drawable who, Runnable what, long when) { - if (mCallback != null) { - mCallback.scheduleDrawable(this, what, when); - } - } - - public void unscheduleDrawable(Drawable who, Runnable what) { - if (mCallback != null) { - mCallback.unscheduleDrawable(this, what); - } - } - - @Override - public boolean getPadding(Rect padding) { - return mState.mDrawable.getPadding(padding); - } - - @Override - public boolean setVisible(boolean visible, boolean restart) { - mState.mDrawable.setVisible(visible, restart); - return super.setVisible(visible, restart); - } - - @Override - public boolean isStateful() { - return mState.mDrawable.isStateful(); - } - - @Override - protected boolean onStateChange(int[] state) { - boolean changed = mState.mDrawable.setState(state); - onBoundsChange(getBounds()); - return changed; - } - - @Override - protected boolean onLevelChange(int level) { - mState.mDrawable.setLevel(level); - onBoundsChange(getBounds()); - - mState.mCurrentDegrees = mState.mFromDegrees + - (mState.mToDegrees - mState.mFromDegrees) * - ((float) level / MAX_LEVEL); - - invalidateSelf(); - return true; - } - - @Override - protected void onBoundsChange(Rect bounds) { - mState.mDrawable.setBounds(bounds.left, bounds.top, - bounds.right, bounds.bottom); - } - - @Override - public int getIntrinsicWidth() { - return mState.mDrawable.getIntrinsicWidth(); - } - - @Override - public int getIntrinsicHeight() { - return mState.mDrawable.getIntrinsicHeight(); - } - - @Override - public ConstantState getConstantState() { - if (mState.canConstantState()) { - mState.mChangingConfigurations = super.getChangingConfigurations(); - return mState; - } - return null; - } - - @Override - public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) - throws XmlPullParserException, IOException { - - TypedArray a = r.obtainAttributes(attrs, - com.android.internal.R.styleable.RotateDrawable); - - super.inflateWithAttributes(r, parser, a, - com.android.internal.R.styleable.RotateDrawable_visible); - - TypedValue tv = a.peekValue(com.android.internal.R.styleable.RotateDrawable_pivotX); - boolean pivotXRel = tv.type == TypedValue.TYPE_FRACTION; - float pivotX = pivotXRel ? tv.getFraction(1.0f, 1.0f) : tv.getFloat(); - - tv = a.peekValue(com.android.internal.R.styleable.RotateDrawable_pivotY); - boolean pivotYRel = tv.type == TypedValue.TYPE_FRACTION; - float pivotY = pivotYRel ? tv.getFraction(1.0f, 1.0f) : tv.getFloat(); - - float fromDegrees = a.getFloat( - com.android.internal.R.styleable.RotateDrawable_fromDegrees, 0.0f); - float toDegrees = a.getFloat( - com.android.internal.R.styleable.RotateDrawable_toDegrees, 360.0f); - - toDegrees = Math.max(fromDegrees, toDegrees); - - int res = a.getResourceId( - com.android.internal.R.styleable.RotateDrawable_drawable, 0); - Drawable drawable = null; - if (res > 0) { - drawable = r.getDrawable(res); - } - - a.recycle(); - - int outerDepth = parser.getDepth(); - int type; - while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && - (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { - - if (type != XmlPullParser.START_TAG) { - continue; - } - - if ((drawable = Drawable.createFromXmlInner(r, parser, attrs)) == null) { - Log.w("drawable", "Bad element underRepresents the state of a rotation for a given drawable. The same - * rotate drawable can be invoked with different states to drive several - * rotations at the same time.
- */ - final static class RotateState extends Drawable.ConstantState { - Drawable mDrawable; - - int mChangingConfigurations; - - boolean mPivotXRel; - float mPivotX; - boolean mPivotYRel; - float mPivotY; - - float mFromDegrees; - float mToDegrees; - - float mCurrentDegrees; - - private boolean mCanConstantState; - private boolean mCheckedConstantState; - - public RotateState(RotateState source, RotateDrawable owner) { - if (source != null) { - mDrawable = source.mDrawable.getConstantState().newDrawable(); - mDrawable.setCallback(owner); - mPivotXRel = source.mPivotXRel; - mPivotX = source.mPivotX; - mPivotYRel = source.mPivotYRel; - mPivotY = source.mPivotY; - mFromDegrees = mCurrentDegrees = source.mFromDegrees; - mToDegrees = source.mToDegrees; - mCanConstantState = mCheckedConstantState = true; - } - } - - @Override - public Drawable newDrawable() { - return new RotateDrawable(this); - } - - @Override - public int getChangingConfigurations() { - return mChangingConfigurations; - } - - public boolean canConstantState() { - if (!mCheckedConstantState) { - mCanConstantState = mDrawable.getConstantState() != null; - mCheckedConstantState = true; - } - - return mCanConstantState; - } - } -} diff --git a/graphics/java/android/graphics/drawable/ScaleDrawable.java b/graphics/java/android/graphics/drawable/ScaleDrawable.java deleted file mode 100644 index 7125ab1..0000000 --- a/graphics/java/android/graphics/drawable/ScaleDrawable.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.graphics.drawable; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; - -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.graphics.*; -import android.view.Gravity; -import android.util.AttributeSet; - -import java.io.IOException; - -/** - * A Drawable that changes the size of another Drawable based on its current - * level value. You can control how much the child Drawable changes in width - * and height based on the level, as well as a gravity to control where it is - * placed in its overall container. Most often used to implement things like - * progress bars. - * - *It can be defined in an XML file with the <scale>
element.
It can be defined in an XML file with the <selector>
element.
- * Each state Drawable is defined in a nested <item>
element.
- * It can be defined in an XML file with the <transition>
element.
- * Each Drawable in the transition is defined in a nested <item>
.
- *