file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
Example/Pods/WebP/WebP.framework/Headers/decode.h
C/C++ Header
// Copyright 2010 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Main decoding functions for WebP images. // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_DECODE_H_ #define WEBP_WEBP_DECODE_H_ #include "./types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_DECODER_ABI_VERSION 0x0203 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum VP8StatusCode VP8StatusCode; // typedef enum WEBP_CSP_MODE WEBP_CSP_MODE; typedef struct WebPRGBABuffer WebPRGBABuffer; typedef struct WebPYUVABuffer WebPYUVABuffer; typedef struct WebPDecBuffer WebPDecBuffer; typedef struct WebPIDecoder WebPIDecoder; typedef struct WebPBitstreamFeatures WebPBitstreamFeatures; typedef struct WebPDecoderOptions WebPDecoderOptions; typedef struct WebPDecoderConfig WebPDecoderConfig; // Return the decoder's version number, packed in hexadecimal using 8bits for // each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN(int) WebPGetDecoderVersion(void); // Retrieve basic header information: width, height. // This function will also validate the header and return 0 in // case of formatting error. // Pointers 'width' and 'height' can be passed NULL if deemed irrelevant. WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size, int* width, int* height); // Decodes WebP images pointed to by 'data' and returns RGBA samples, along // with the dimensions in *width and *height. The ordering of samples in // memory is R, G, B, A, R, G, B, A... in scan order (endian-independent). // The returned pointer should be deleted calling free(). // Returns NULL in case of error. WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data. WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data. WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data. // If the bitstream contains transparency, it is ignored. WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size, int* width, int* height); // Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data. WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size, int* width, int* height); // Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer // returned is the Y samples buffer. Upon return, *u and *v will point to // the U and V chroma data. These U and V buffers need NOT be free()'d, // unlike the returned Y luma one. The dimension of the U and V planes // are both (*width + 1) / 2 and (*height + 1)/ 2. // Upon return, the Y buffer has a stride returned as '*stride', while U and V // have a common stride returned as '*uv_stride'. // Return NULL in case of error. // (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size, int* width, int* height, uint8_t** u, uint8_t** v, int* stride, int* uv_stride); // These five functions are variants of the above ones, that decode the image // directly into a pre-allocated buffer 'output_buffer'. The maximum storage // available in this buffer is indicated by 'output_buffer_size'. If this // storage is not sufficient (or an error occurred), NULL is returned. // Otherwise, output_buffer is returned, for convenience. // The parameter 'output_stride' specifies the distance (in bytes) // between scanlines. Hence, output_buffer_size is expected to be at least // output_stride x picture-height. WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // RGB and BGR variants. Here too the transparency information, if present, // will be dropped and ignored. WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto( const uint8_t* data, size_t data_size, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly // into pre-allocated luma/chroma plane buffers. This function requires the // strides to be passed: one for the luma plane and one for each of the // chroma ones. The size of each plane buffer is passed as 'luma_size', // 'u_size' and 'v_size' respectively. // Pointer to the luma plane ('*luma') is returned or NULL if an error occurred // during decoding (or because some buffers were found to be too small). WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto( const uint8_t* data, size_t data_size, uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride); //------------------------------------------------------------------------------ // Output colorspaces and buffer // Colorspaces // Note: the naming describes the byte-ordering of packed samples in memory. // For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,... // Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels. // RGBA-4444 and RGB-565 colorspaces are represented by following byte-order: // RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ... // RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ... // In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for // these two modes: // RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ... // RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ... typedef enum WEBP_CSP_MODE { MODE_RGB = 0, MODE_RGBA = 1, MODE_BGR = 2, MODE_BGRA = 3, MODE_ARGB = 4, MODE_RGBA_4444 = 5, MODE_RGB_565 = 6, // RGB-premultiplied transparent modes (alpha value is preserved) MODE_rgbA = 7, MODE_bgrA = 8, MODE_Argb = 9, MODE_rgbA_4444 = 10, // YUV modes must come after RGB ones. MODE_YUV = 11, MODE_YUVA = 12, // yuv 4:2:0 MODE_LAST = 13 } WEBP_CSP_MODE; // Some useful macros: static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) { return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb || mode == MODE_rgbA_4444); } static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) { return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB || mode == MODE_RGBA_4444 || mode == MODE_YUVA || WebPIsPremultipliedMode(mode)); } static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) { return (mode < MODE_YUV); } //------------------------------------------------------------------------------ // WebPDecBuffer: Generic structure for describing the output sample buffer. struct WebPRGBABuffer { // view as RGBA uint8_t* rgba; // pointer to RGBA samples int stride; // stride in bytes from one scanline to the next. size_t size; // total size of the *rgba buffer. }; struct WebPYUVABuffer { // view as YUVA uint8_t* y, *u, *v, *a; // pointer to luma, chroma U/V, alpha samples int y_stride; // luma stride int u_stride, v_stride; // chroma strides int a_stride; // alpha stride size_t y_size; // luma plane size size_t u_size, v_size; // chroma planes size size_t a_size; // alpha-plane size }; // Output buffer struct WebPDecBuffer { WEBP_CSP_MODE colorspace; // Colorspace. int width, height; // Dimensions. int is_external_memory; // If true, 'internal_memory' pointer is not used. union { WebPRGBABuffer RGBA; WebPYUVABuffer YUVA; } u; // Nameless union of buffer parameters. uint32_t pad[4]; // padding for later use uint8_t* private_memory; // Internally allocated memory (only when // is_external_memory is false). Should not be used // externally, but accessed via the buffer union. }; // Internal, version-checked, entry point WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int); // Initialize the structure as empty. Must be called before any other use. // Returns false in case of version mismatch static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) { return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION); } // Free any memory associated with the buffer. Must always be called last. // Note: doesn't free the 'buffer' structure itself. WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer); //------------------------------------------------------------------------------ // Enumeration of the status codes typedef enum VP8StatusCode { VP8_STATUS_OK = 0, VP8_STATUS_OUT_OF_MEMORY, VP8_STATUS_INVALID_PARAM, VP8_STATUS_BITSTREAM_ERROR, VP8_STATUS_UNSUPPORTED_FEATURE, VP8_STATUS_SUSPENDED, VP8_STATUS_USER_ABORT, VP8_STATUS_NOT_ENOUGH_DATA } VP8StatusCode; //------------------------------------------------------------------------------ // Incremental decoding // // This API allows streamlined decoding of partial data. // Picture can be incrementally decoded as data become available thanks to the // WebPIDecoder object. This object can be left in a SUSPENDED state if the // picture is only partially decoded, pending additional input. // Code example: // // WebPInitDecBuffer(&buffer); // buffer.colorspace = mode; // ... // WebPIDecoder* idec = WebPINewDecoder(&buffer); // while (has_more_data) { // // ... (get additional data) // status = WebPIAppend(idec, new_data, new_data_size); // if (status != VP8_STATUS_SUSPENDED || // break; // } // // // The above call decodes the current available buffer. // // Part of the image can now be refreshed by calling to // // WebPIDecGetRGB()/WebPIDecGetYUVA() etc. // } // WebPIDelete(idec); // Creates a new incremental decoder with the supplied buffer parameter. // This output_buffer can be passed NULL, in which case a default output buffer // is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer' // is kept, which means that the lifespan of 'output_buffer' must be larger than // that of the returned WebPIDecoder object. // The supplied 'output_buffer' content MUST NOT be changed between calls to // WebPIAppend() or WebPIUpdate() unless 'output_buffer.is_external_memory' is // set to 1. In such a case, it is allowed to modify the pointers, size and // stride of output_buffer.u.RGBA or output_buffer.u.YUVA, provided they remain // within valid bounds. // All other fields of WebPDecBuffer MUST remain constant between calls. // Returns NULL if the allocation failed. WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer); // This function allocates and initializes an incremental-decoder object, which // will output the RGB/A samples specified by 'csp' into a preallocated // buffer 'output_buffer'. The size of this buffer is at least // 'output_buffer_size' and the stride (distance in bytes between two scanlines) // is specified by 'output_stride'. // Additionally, output_buffer can be passed NULL in which case the output // buffer will be allocated automatically when the decoding starts. The // colorspace 'csp' is taken into account for allocating this buffer. All other // parameters are ignored. // Returns NULL if the allocation failed, or if some parameters are invalid. WEBP_EXTERN(WebPIDecoder*) WebPINewRGB( WEBP_CSP_MODE csp, uint8_t* output_buffer, size_t output_buffer_size, int output_stride); // This function allocates and initializes an incremental-decoder object, which // will output the raw luma/chroma samples into a preallocated planes if // supplied. The luma plane is specified by its pointer 'luma', its size // 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane // is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v // plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer // can be pass NULL in case one is not interested in the transparency plane. // Conversely, 'luma' can be passed NULL if no preallocated planes are supplied. // In this case, the output buffer will be automatically allocated (using // MODE_YUVA) when decoding starts. All parameters are then ignored. // Returns NULL if the allocation failed or if a parameter is invalid. WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA( uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride, uint8_t* a, size_t a_size, int a_stride); // Deprecated version of the above, without the alpha plane. // Kept for backward compatibility. WEBP_EXTERN(WebPIDecoder*) WebPINewYUV( uint8_t* luma, size_t luma_size, int luma_stride, uint8_t* u, size_t u_size, int u_stride, uint8_t* v, size_t v_size, int v_stride); // Deletes the WebPIDecoder object and associated memory. Must always be called // if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded. WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec); // Copies and decodes the next available data. Returns VP8_STATUS_OK when // the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more // data is expected. Returns error in other cases. WEBP_EXTERN(VP8StatusCode) WebPIAppend( WebPIDecoder* idec, const uint8_t* data, size_t data_size); // A variant of the above function to be used when data buffer contains // partial data from the beginning. In this case data buffer is not copied // to the internal memory. // Note that the value of the 'data' pointer can change between calls to // WebPIUpdate, for instance when the data buffer is resized to fit larger data. WEBP_EXTERN(VP8StatusCode) WebPIUpdate( WebPIDecoder* idec, const uint8_t* data, size_t data_size); // Returns the RGB/A image decoded so far. Returns NULL if output params // are not initialized yet. The RGB/A output type corresponds to the colorspace // specified during call to WebPINewDecoder() or WebPINewRGB(). // *last_y is the index of last decoded row in raster scan order. Some pointers // (*last_y, *width etc.) can be NULL if corresponding information is not // needed. WEBP_EXTERN(uint8_t*) WebPIDecGetRGB( const WebPIDecoder* idec, int* last_y, int* width, int* height, int* stride); // Same as above function to get a YUVA image. Returns pointer to the luma // plane or NULL in case of error. If there is no alpha information // the alpha pointer '*a' will be returned NULL. WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA( const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v, uint8_t** a, int* width, int* height, int* stride, int* uv_stride, int* a_stride); // Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the // alpha information (if present). Kept for backward compatibility. static WEBP_INLINE uint8_t* WebPIDecGetYUV( const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v, int* width, int* height, int* stride, int* uv_stride) { return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height, stride, uv_stride, NULL); } // Generic call to retrieve information about the displayable area. // If non NULL, the left/right/width/height pointers are filled with the visible // rectangular area so far. // Returns NULL in case the incremental decoder object is in an invalid state. // Otherwise returns the pointer to the internal representation. This structure // is read-only, tied to WebPIDecoder's lifespan and should not be modified. WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea( const WebPIDecoder* idec, int* left, int* top, int* width, int* height); //------------------------------------------------------------------------------ // Advanced decoding parametrization // // Code sample for using the advanced decoding API /* // A) Init a configuration object WebPDecoderConfig config; CHECK(WebPInitDecoderConfig(&config)); // B) optional: retrieve the bitstream's features. CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK); // C) Adjust 'config', if needed config.no_fancy_upsampling = 1; config.output.colorspace = MODE_BGRA; // etc. // Note that you can also make config.output point to an externally // supplied memory buffer, provided it's big enough to store the decoded // picture. Otherwise, config.output will just be used to allocate memory // and store the decoded picture. // D) Decode! CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK); // E) Decoded image is now in config.output (and config.output.u.RGBA) // F) Reclaim memory allocated in config's object. It's safe to call // this function even if the memory is external and wasn't allocated // by WebPDecode(). WebPFreeDecBuffer(&config.output); */ // Features gathered from the bitstream struct WebPBitstreamFeatures { int width; // Width in pixels, as read from the bitstream. int height; // Height in pixels, as read from the bitstream. int has_alpha; // True if the bitstream contains an alpha channel. int has_animation; // True if the bitstream is an animation. int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless // Unused for now: int no_incremental_decoding; // if true, using incremental decoding is not // recommended. int rotate; // TODO(later) int uv_sampling; // should be 0 for now. TODO(later) uint32_t pad[2]; // padding for later use }; // Internal, version-checked, entry point WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal( const uint8_t*, size_t, WebPBitstreamFeatures*, int); // Retrieve features from the bitstream. The *features structure is filled // with information gathered from the bitstream. // Returns VP8_STATUS_OK when the features are successfully retrieved. Returns // VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the // features from headers. Returns error in other cases. static WEBP_INLINE VP8StatusCode WebPGetFeatures( const uint8_t* data, size_t data_size, WebPBitstreamFeatures* features) { return WebPGetFeaturesInternal(data, data_size, features, WEBP_DECODER_ABI_VERSION); } // Decoding options struct WebPDecoderOptions { int bypass_filtering; // if true, skip the in-loop filtering int no_fancy_upsampling; // if true, use faster pointwise upsampler int use_cropping; // if true, cropping is applied _first_ int crop_left, crop_top; // top-left position for cropping. // Will be snapped to even values. int crop_width, crop_height; // dimension of the cropping area int use_scaling; // if true, scaling is applied _afterward_ int scaled_width, scaled_height; // final resolution int use_threads; // if true, use multi-threaded decoding int dithering_strength; // dithering strength (0=Off, 100=full) #if WEBP_DECODER_ABI_VERSION > 0x0203 int flip; // flip output vertically #endif #if WEBP_DECODER_ABI_VERSION > 0x0204 int alpha_dithering_strength; // alpha dithering strength in [0..100] #endif // Unused for now: int force_rotation; // forced rotation (to be applied _last_) int no_enhancement; // if true, discard enhancement layer #if WEBP_DECODER_ABI_VERSION < 0x0203 uint32_t pad[5]; // padding for later use #elif WEBP_DECODER_ABI_VERSION < 0x0204 uint32_t pad[4]; // padding for later use #else uint32_t pad[3]; // padding for later use #endif }; // Main object storing the configuration for advanced decoding. struct WebPDecoderConfig { WebPBitstreamFeatures input; // Immutable bitstream features (optional) WebPDecBuffer output; // Output buffer (can point to external mem) WebPDecoderOptions options; // Decoding options }; // Internal, version-checked, entry point WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int); // Initialize the configuration as empty. This function must always be // called first, unless WebPGetFeatures() is to be called. // Returns false in case of mismatched version. static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) { return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION); } // Instantiate a new incremental decoder object with the requested // configuration. The bitstream can be passed using 'data' and 'data_size' // parameter, in which case the features will be parsed and stored into // config->input. Otherwise, 'data' can be NULL and no parsing will occur. // Note that 'config' can be NULL too, in which case a default configuration // is used. // The return WebPIDecoder object must always be deleted calling WebPIDelete(). // Returns NULL in case of error (and config->status will then reflect // the error condition). WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size, WebPDecoderConfig* config); // Non-incremental version. This version decodes the full data at once, taking // 'config' into account. Returns decoding status (which should be VP8_STATUS_OK // if the decoding was successful). WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size, WebPDecoderConfig* config); #ifdef __cplusplus } // extern "C" #endif #endif /* WEBP_WEBP_DECODE_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/demux.h
C/C++ Header
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Demux API. // Enables extraction of image and extended format data from WebP files. // Code Example: Demuxing WebP data to extract all the frames, ICC profile // and EXIF/XMP metadata. /* WebPDemuxer* demux = WebPDemux(&webp_data); uint32_t width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH); uint32_t height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT); // ... (Get information about the features present in the WebP file). uint32_t flags = WebPDemuxGetI(demux, WEBP_FF_FORMAT_FLAGS); // ... (Iterate over all frames). WebPIterator iter; if (WebPDemuxGetFrame(demux, 1, &iter)) { do { // ... (Consume 'iter'; e.g. Decode 'iter.fragment' with WebPDecode(), // ... and get other frame properties like width, height, offsets etc. // ... see 'struct WebPIterator' below for more info). } while (WebPDemuxNextFrame(&iter)); WebPDemuxReleaseIterator(&iter); } // ... (Extract metadata). WebPChunkIterator chunk_iter; if (flags & ICCP_FLAG) WebPDemuxGetChunk(demux, "ICCP", 1, &chunk_iter); // ... (Consume the ICC profile in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); if (flags & EXIF_FLAG) WebPDemuxGetChunk(demux, "EXIF", 1, &chunk_iter); // ... (Consume the EXIF metadata in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); if (flags & XMP_FLAG) WebPDemuxGetChunk(demux, "XMP ", 1, &chunk_iter); // ... (Consume the XMP metadata in 'chunk_iter.chunk'). WebPDemuxReleaseChunkIterator(&chunk_iter); WebPDemuxDelete(demux); */ #ifndef WEBP_WEBP_DEMUX_H_ #define WEBP_WEBP_DEMUX_H_ #include "./mux_types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_DEMUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPDemuxState WebPDemuxState; // typedef enum WebPFormatFeature WebPFormatFeature; typedef struct WebPDemuxer WebPDemuxer; typedef struct WebPIterator WebPIterator; typedef struct WebPChunkIterator WebPChunkIterator; //------------------------------------------------------------------------------ // Returns the version number of the demux library, packed in hexadecimal using // 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN(int) WebPGetDemuxVersion(void); //------------------------------------------------------------------------------ // Life of a Demux object typedef enum WebPDemuxState { WEBP_DEMUX_PARSE_ERROR = -1, // An error occurred while parsing. WEBP_DEMUX_PARSING_HEADER = 0, // Not enough data to parse full header. WEBP_DEMUX_PARSED_HEADER = 1, // Header parsing complete, // data may be available. WEBP_DEMUX_DONE = 2 // Entire file has been parsed. } WebPDemuxState; // Internal, version-checked, entry point WEBP_EXTERN(WebPDemuxer*) WebPDemuxInternal( const WebPData*, int, WebPDemuxState*, int); // Parses the full WebP file given by 'data'. // Returns a WebPDemuxer object on successful parse, NULL otherwise. static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) { return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION); } // Parses the possibly incomplete WebP file given by 'data'. // If 'state' is non-NULL it will be set to indicate the status of the demuxer. // Returns NULL in case of error or if there isn't enough data to start parsing; // and a WebPDemuxer object on successful parse. // Note that WebPDemuxer keeps internal pointers to 'data' memory segment. // If this data is volatile, the demuxer object should be deleted (by calling // WebPDemuxDelete()) and WebPDemuxPartial() called again on the new data. // This is usually an inexpensive operation. static WEBP_INLINE WebPDemuxer* WebPDemuxPartial( const WebPData* data, WebPDemuxState* state) { return WebPDemuxInternal(data, 1, state, WEBP_DEMUX_ABI_VERSION); } // Frees memory associated with 'dmux'. WEBP_EXTERN(void) WebPDemuxDelete(WebPDemuxer* dmux); //------------------------------------------------------------------------------ // Data/information extraction. typedef enum WebPFormatFeature { WEBP_FF_FORMAT_FLAGS, // Extended format flags present in the 'VP8X' chunk. WEBP_FF_CANVAS_WIDTH, WEBP_FF_CANVAS_HEIGHT, WEBP_FF_LOOP_COUNT, WEBP_FF_BACKGROUND_COLOR, WEBP_FF_FRAME_COUNT // Number of frames present in the demux object. // In case of a partial demux, this is the number of // frames seen so far, with the last frame possibly // being partial. } WebPFormatFeature; // Get the 'feature' value from the 'dmux'. // NOTE: values are only valid if WebPDemux() was used or WebPDemuxPartial() // returned a state > WEBP_DEMUX_PARSING_HEADER. WEBP_EXTERN(uint32_t) WebPDemuxGetI( const WebPDemuxer* dmux, WebPFormatFeature feature); //------------------------------------------------------------------------------ // Frame iteration. struct WebPIterator { int frame_num; int num_frames; // equivalent to WEBP_FF_FRAME_COUNT. int fragment_num; int num_fragments; int x_offset, y_offset; // offset relative to the canvas. int width, height; // dimensions of this frame or fragment. int duration; // display duration in milliseconds. WebPMuxAnimDispose dispose_method; // dispose method for the frame. int complete; // true if 'fragment' contains a full frame. partial images // may still be decoded with the WebP incremental decoder. WebPData fragment; // The frame or fragment given by 'frame_num' and // 'fragment_num'. int has_alpha; // True if the frame or fragment contains transparency. WebPMuxAnimBlend blend_method; // Blend operation for the frame. uint32_t pad[2]; // padding for later use. void* private_; // for internal use only. }; // Retrieves frame 'frame_number' from 'dmux'. // 'iter->fragment' points to the first fragment on return from this function. // Individual fragments may be extracted using WebPDemuxSelectFragment(). // Setting 'frame_number' equal to 0 will return the last frame of the image. // Returns false if 'dmux' is NULL or frame 'frame_number' is not present. // Call WebPDemuxReleaseIterator() when use of the iterator is complete. // NOTE: 'dmux' must persist for the lifetime of 'iter'. WEBP_EXTERN(int) WebPDemuxGetFrame( const WebPDemuxer* dmux, int frame_number, WebPIterator* iter); // Sets 'iter->fragment' to point to the next ('iter->frame_num' + 1) or // previous ('iter->frame_num' - 1) frame. These functions do not loop. // Returns true on success, false otherwise. WEBP_EXTERN(int) WebPDemuxNextFrame(WebPIterator* iter); WEBP_EXTERN(int) WebPDemuxPrevFrame(WebPIterator* iter); // Sets 'iter->fragment' to reflect fragment number 'fragment_num'. // Returns true if fragment 'fragment_num' is present, false otherwise. WEBP_EXTERN(int) WebPDemuxSelectFragment(WebPIterator* iter, int fragment_num); // Releases any memory associated with 'iter'. // Must be called before any subsequent calls to WebPDemuxGetChunk() on the same // iter. Also, must be called before destroying the associated WebPDemuxer with // WebPDemuxDelete(). WEBP_EXTERN(void) WebPDemuxReleaseIterator(WebPIterator* iter); //------------------------------------------------------------------------------ // Chunk iteration. struct WebPChunkIterator { // The current and total number of chunks with the fourcc given to // WebPDemuxGetChunk(). int chunk_num; int num_chunks; WebPData chunk; // The payload of the chunk. uint32_t pad[6]; // padding for later use void* private_; }; // Retrieves the 'chunk_number' instance of the chunk with id 'fourcc' from // 'dmux'. // 'fourcc' is a character array containing the fourcc of the chunk to return, // e.g., "ICCP", "XMP ", "EXIF", etc. // Setting 'chunk_number' equal to 0 will return the last chunk in a set. // Returns true if the chunk is found, false otherwise. Image related chunk // payloads are accessed through WebPDemuxGetFrame() and related functions. // Call WebPDemuxReleaseChunkIterator() when use of the iterator is complete. // NOTE: 'dmux' must persist for the lifetime of the iterator. WEBP_EXTERN(int) WebPDemuxGetChunk(const WebPDemuxer* dmux, const char fourcc[4], int chunk_number, WebPChunkIterator* iter); // Sets 'iter->chunk' to point to the next ('iter->chunk_num' + 1) or previous // ('iter->chunk_num' - 1) chunk. These functions do not loop. // Returns true on success, false otherwise. WEBP_EXTERN(int) WebPDemuxNextChunk(WebPChunkIterator* iter); WEBP_EXTERN(int) WebPDemuxPrevChunk(WebPChunkIterator* iter); // Releases any memory associated with 'iter'. // Must be called before destroying the associated WebPDemuxer with // WebPDemuxDelete(). WEBP_EXTERN(void) WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter); //------------------------------------------------------------------------------ #ifdef __cplusplus } // extern "C" #endif #endif /* WEBP_WEBP_DEMUX_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/encode.h
C/C++ Header
// Copyright 2011 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // WebP encoder: main interface // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_ENCODE_H_ #define WEBP_WEBP_ENCODE_H_ #include "./types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_ENCODER_ABI_VERSION 0x0202 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPImageHint WebPImageHint; // typedef enum WebPEncCSP WebPEncCSP; // typedef enum WebPPreset WebPPreset; // typedef enum WebPEncodingError WebPEncodingError; typedef struct WebPConfig WebPConfig; typedef struct WebPPicture WebPPicture; // main structure for I/O typedef struct WebPAuxStats WebPAuxStats; typedef struct WebPMemoryWriter WebPMemoryWriter; // Return the encoder's version number, packed in hexadecimal using 8bits for // each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN(int) WebPGetEncoderVersion(void); //------------------------------------------------------------------------------ // One-stop-shop call! No questions asked: // Returns the size of the compressed data (pointed to by *output), or 0 if // an error occurred. The compressed data must be released by the caller // using the call 'free(*output)'. // These functions compress using the lossy format, and the quality_factor // can go from 0 (smaller output, lower quality) to 100 (best quality, // larger output). WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba, int width, int height, int stride, float quality_factor, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra, int width, int height, int stride, float quality_factor, uint8_t** output); // These functions are the equivalent of the above, but compressing in a // lossless manner. Files are usually larger than lossy format, but will // not suffer any compression loss. WEBP_EXTERN(size_t) WebPEncodeLosslessRGB(const uint8_t* rgb, int width, int height, int stride, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeLosslessBGR(const uint8_t* bgr, int width, int height, int stride, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeLosslessRGBA(const uint8_t* rgba, int width, int height, int stride, uint8_t** output); WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra, int width, int height, int stride, uint8_t** output); //------------------------------------------------------------------------------ // Coding parameters // Image characteristics hint for the underlying encoder. typedef enum WebPImageHint { WEBP_HINT_DEFAULT = 0, // default preset. WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc). WEBP_HINT_LAST } WebPImageHint; // Compression parameters. struct WebPConfig { int lossless; // Lossless encoding (0=lossy(default), 1=lossless). float quality; // between 0 (smallest file) and 100 (biggest) int method; // quality/speed trade-off (0=fast, 6=slower-better) WebPImageHint image_hint; // Hint for image type (lossless only for now). // Parameters related to lossy compression only: int target_size; // if non-zero, set the desired target size in bytes. // Takes precedence over the 'compression' parameter. float target_PSNR; // if non-zero, specifies the minimal distortion to // try to achieve. Takes precedence over target_size. int segments; // maximum number of segments to use, in [1..4] int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum. int filter_strength; // range: [0 = off .. 100 = strongest] int filter_sharpness; // range: [0 = off .. 7 = least sharp] int filter_type; // filtering type: 0 = simple, 1 = strong (only used // if filter_strength > 0 or autofilter > 0) int autofilter; // Auto adjust filter's strength [0 = off, 1 = on] int alpha_compression; // Algorithm for encoding the alpha plane (0 = none, // 1 = compressed with WebP lossless). Default is 1. int alpha_filtering; // Predictive filtering method for alpha plane. // 0: none, 1: fast, 2: best. Default if 1. int alpha_quality; // Between 0 (smallest size) and 100 (lossless). // Default is 100. int pass; // number of entropy-analysis passes (in [1..10]). int show_compressed; // if true, export the compressed picture back. // In-loop filtering is not applied. int preprocessing; // preprocessing filter: // 0=none, 1=segment-smooth, 2=pseudo-random dithering int partitions; // log2(number of token partitions) in [0..3]. Default // is set to 0 for easier progressive decoding. int partition_limit; // quality degradation allowed to fit the 512k limit // on prediction modes coding (0: no degradation, // 100: maximum possible degradation). int emulate_jpeg_size; // If true, compression parameters will be remapped // to better match the expected output size from // JPEG compression. Generally, the output size will // be similar but the degradation will be lower. int thread_level; // If non-zero, try and use multi-threaded encoding. int low_memory; // If set, reduce memory usage (but increase CPU use). uint32_t pad[5]; // padding for later use }; // Enumerate some predefined settings for WebPConfig, depending on the type // of source picture. These presets are used when calling WebPConfigPreset(). typedef enum WebPPreset { WEBP_PRESET_DEFAULT = 0, // default preset. WEBP_PRESET_PICTURE, // digital picture, like portrait, inner shot WEBP_PRESET_PHOTO, // outdoor photograph, with natural lighting WEBP_PRESET_DRAWING, // hand or line drawing, with high-contrast details WEBP_PRESET_ICON, // small-sized colorful images WEBP_PRESET_TEXT // text-like } WebPPreset; // Internal, version-checked, entry point WEBP_EXTERN(int) WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int); // Should always be called, to initialize a fresh WebPConfig structure before // modification. Returns false in case of version mismatch. WebPConfigInit() // must have succeeded before using the 'config' object. // Note that the default values are lossless=0 and quality=75. static WEBP_INLINE int WebPConfigInit(WebPConfig* config) { return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f, WEBP_ENCODER_ABI_VERSION); } // This function will initialize the configuration according to a predefined // set of parameters (referred to by 'preset') and a given quality factor. // This function can be called as a replacement to WebPConfigInit(). Will // return false in case of error. static WEBP_INLINE int WebPConfigPreset(WebPConfig* config, WebPPreset preset, float quality) { return WebPConfigInitInternal(config, preset, quality, WEBP_ENCODER_ABI_VERSION); } #if WEBP_ENCODER_ABI_VERSION > 0x0202 // Activate the lossless compression mode with the desired efficiency level // between 0 (fastest, lowest compression) and 9 (slower, best compression). // A good default level is '6', providing a fair tradeoff between compression // speed and final compressed size. // This function will overwrite several fields from config: 'method', 'quality' // and 'lossless'. Returns false in case of parameter error. WEBP_EXTERN(int) WebPConfigLosslessPreset(WebPConfig* config, int level); #endif // Returns true if 'config' is non-NULL and all configuration parameters are // within their valid ranges. WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* config); //------------------------------------------------------------------------------ // Input / Output // Structure for storing auxiliary statistics (mostly for lossy encoding). struct WebPAuxStats { int coded_size; // final size float PSNR[5]; // peak-signal-to-noise ratio for Y/U/V/All/Alpha int block_count[3]; // number of intra4/intra16/skipped macroblocks int header_bytes[2]; // approximate number of bytes spent for header // and mode-partition #0 int residual_bytes[3][4]; // approximate number of bytes spent for // DC/AC/uv coefficients for each (0..3) segments. int segment_size[4]; // number of macroblocks in each segments int segment_quant[4]; // quantizer values for each segments int segment_level[4]; // filtering strength for each segments [0..63] int alpha_data_size; // size of the transparency data int layer_data_size; // size of the enhancement layer data // lossless encoder statistics uint32_t lossless_features; // bit0:predictor bit1:cross-color transform // bit2:subtract-green bit3:color indexing int histogram_bits; // number of precision bits of histogram int transform_bits; // precision bits for transform int cache_bits; // number of bits for color cache lookup int palette_size; // number of color in palette, if used int lossless_size; // final lossless size uint32_t pad[4]; // padding for later use }; // Signature for output function. Should return true if writing was successful. // data/data_size is the segment of data to write, and 'picture' is for // reference (and so one can make use of picture->custom_ptr). typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size, const WebPPicture* picture); // WebPMemoryWrite: a special WebPWriterFunction that writes to memory using // the following WebPMemoryWriter object (to be set as a custom_ptr). struct WebPMemoryWriter { uint8_t* mem; // final buffer (of size 'max_size', larger than 'size'). size_t size; // final size size_t max_size; // total capacity uint32_t pad[1]; // padding for later use }; // The following must be called first before any use. WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer); #if WEBP_ENCODER_ABI_VERSION > 0x0203 // The following must be called to deallocate writer->mem memory. The 'writer' // object itself is not deallocated. WEBP_EXTERN(void) WebPMemoryWriterClear(WebPMemoryWriter* writer); #endif // The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon // completion, writer.mem and writer.size will hold the coded data. #if WEBP_ENCODER_ABI_VERSION > 0x0203 // writer.mem must be freed by calling WebPMemoryWriterClear. #else // writer.mem must be freed by calling 'free(writer.mem)'. #endif WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size, const WebPPicture* picture); // Progress hook, called from time to time to report progress. It can return // false to request an abort of the encoding process, or true otherwise if // everything is OK. typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture); // Color spaces. typedef enum WebPEncCSP { // chroma sampling WEBP_YUV420 = 0, // 4:2:0 WEBP_YUV420A = 4, // alpha channel variant WEBP_CSP_UV_MASK = 3, // bit-mask to get the UV sampling factors WEBP_CSP_ALPHA_BIT = 4 // bit that is set if alpha is present } WebPEncCSP; // Encoding error conditions. typedef enum WebPEncodingError { VP8_ENC_OK = 0, VP8_ENC_ERROR_OUT_OF_MEMORY, // memory error allocating objects VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY, // memory error while flushing bits VP8_ENC_ERROR_NULL_PARAMETER, // a pointer parameter is NULL VP8_ENC_ERROR_INVALID_CONFIGURATION, // configuration is invalid VP8_ENC_ERROR_BAD_DIMENSION, // picture has invalid width/height VP8_ENC_ERROR_PARTITION0_OVERFLOW, // partition is bigger than 512k VP8_ENC_ERROR_PARTITION_OVERFLOW, // partition is bigger than 16M VP8_ENC_ERROR_BAD_WRITE, // error while flushing bytes VP8_ENC_ERROR_FILE_TOO_BIG, // file is bigger than 4G VP8_ENC_ERROR_USER_ABORT, // abort request by user VP8_ENC_ERROR_LAST // list terminator. always last. } WebPEncodingError; // maximum width/height allowed (inclusive), in pixels #define WEBP_MAX_DIMENSION 16383 // Main exchange structure (input samples, output bytes, statistics) struct WebPPicture { // INPUT ////////////// // Main flag for encoder selecting between ARGB or YUV input. // It is recommended to use ARGB input (*argb, argb_stride) for lossless // compression, and YUV input (*y, *u, *v, etc.) for lossy compression // since these are the respective native colorspace for these formats. int use_argb; // YUV input (mostly used for input to lossy compression) WebPEncCSP colorspace; // colorspace: should be YUV420 for now (=Y'CbCr). int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION) uint8_t *y, *u, *v; // pointers to luma/chroma planes. int y_stride, uv_stride; // luma/chroma strides. uint8_t* a; // pointer to the alpha plane int a_stride; // stride of the alpha plane uint32_t pad1[2]; // padding for later use // ARGB input (mostly used for input to lossless compression) uint32_t* argb; // Pointer to argb (32 bit) plane. int argb_stride; // This is stride in pixels units, not bytes. uint32_t pad2[3]; // padding for later use // OUTPUT /////////////// // Byte-emission hook, to store compressed bytes as they are ready. WebPWriterFunction writer; // can be NULL void* custom_ptr; // can be used by the writer. // map for extra information (only for lossy compression mode) int extra_info_type; // 1: intra type, 2: segment, 3: quant // 4: intra-16 prediction mode, // 5: chroma prediction mode, // 6: bit cost, 7: distortion uint8_t* extra_info; // if not NULL, points to an array of size // ((width + 15) / 16) * ((height + 15) / 16) that // will be filled with a macroblock map, depending // on extra_info_type. // STATS AND REPORTS /////////////////////////// // Pointer to side statistics (updated only if not NULL) WebPAuxStats* stats; // Error code for the latest error encountered during encoding WebPEncodingError error_code; // If not NULL, report progress during encoding. WebPProgressHook progress_hook; void* user_data; // this field is free to be set to any value and // used during callbacks (like progress-report e.g.). uint32_t pad3[3]; // padding for later use // Unused for now uint8_t *pad4, *pad5; uint32_t pad6[8]; // padding for later use // PRIVATE FIELDS //////////////////// void* memory_; // row chunk of memory for yuva planes void* memory_argb_; // and for argb too. void* pad7[2]; // padding for later use }; // Internal, version-checked, entry point WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture*, int); // Should always be called, to initialize the structure. Returns false in case // of version mismatch. WebPPictureInit() must have succeeded before using the // 'picture' object. // Note that, by default, use_argb is false and colorspace is WEBP_YUV420. static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) { return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION); } //------------------------------------------------------------------------------ // WebPPicture utils // Convenience allocation / deallocation based on picture->width/height: // Allocate y/u/v buffers as per colorspace/width/height specification. // Note! This function will free the previous buffer if needed. // Returns false in case of memory error. WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* picture); // Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*(). // Note that this function does _not_ free the memory used by the 'picture' // object itself. // Besides memory (which is reclaimed) all other fields of 'picture' are // preserved. WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture); // Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return, *dst // will fully own the copied pixels (this is not a view). The 'dst' picture need // not be initialized as its content is overwritten. // Returns false in case of memory allocation error. WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst); // Compute PSNR, SSIM or LSIM distortion metric between two pictures. // Result is in dB, stores in result[] in the Y/U/V/Alpha/All order. // Returns false in case of error (src and ref don't have same dimension, ...) // Warning: this function is rather CPU-intensive. WEBP_EXTERN(int) WebPPictureDistortion( const WebPPicture* src, const WebPPicture* ref, int metric_type, // 0 = PSNR, 1 = SSIM, 2 = LSIM float result[5]); // self-crops a picture to the rectangle defined by top/left/width/height. // Returns false in case of memory allocation error, or if the rectangle is // outside of the source picture. // The rectangle for the view is defined by the top-left corner pixel // coordinates (left, top) as well as its width and height. This rectangle // must be fully be comprised inside the 'src' source picture. If the source // picture uses the YUV420 colorspace, the top and left coordinates will be // snapped to even values. WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* picture, int left, int top, int width, int height); // Extracts a view from 'src' picture into 'dst'. The rectangle for the view // is defined by the top-left corner pixel coordinates (left, top) as well // as its width and height. This rectangle must be fully be comprised inside // the 'src' source picture. If the source picture uses the YUV420 colorspace, // the top and left coordinates will be snapped to even values. // Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed // ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so, // the original dimension will be lost). Picture 'dst' need not be initialized // with WebPPictureInit() if it is different from 'src', since its content will // be overwritten. // Returns false in case of memory allocation error or invalid parameters. WEBP_EXTERN(int) WebPPictureView(const WebPPicture* src, int left, int top, int width, int height, WebPPicture* dst); // Returns true if the 'picture' is actually a view and therefore does // not own the memory for pixels. WEBP_EXTERN(int) WebPPictureIsView(const WebPPicture* picture); // Rescale a picture to new dimension width x height. // Now gamma correction is applied. // Returns false in case of error (invalid parameter or insufficient memory). WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* pic, int width, int height); // Colorspace conversion function to import RGB samples. // Previous buffer will be free'd, if any. // *rgb buffer should have a size of at least height * rgb_stride. // Returns false in case of memory error. WEBP_EXTERN(int) WebPPictureImportRGB( WebPPicture* picture, const uint8_t* rgb, int rgb_stride); // Same, but for RGBA buffer. WEBP_EXTERN(int) WebPPictureImportRGBA( WebPPicture* picture, const uint8_t* rgba, int rgba_stride); // Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format // input buffer ignoring the alpha channel. Avoids needing to copy the data // to a temporary 24-bit RGB buffer to import the RGB only. WEBP_EXTERN(int) WebPPictureImportRGBX( WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride); // Variants of the above, but taking BGR(A|X) input. WEBP_EXTERN(int) WebPPictureImportBGR( WebPPicture* picture, const uint8_t* bgr, int bgr_stride); WEBP_EXTERN(int) WebPPictureImportBGRA( WebPPicture* picture, const uint8_t* bgra, int bgra_stride); WEBP_EXTERN(int) WebPPictureImportBGRX( WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride); // Converts picture->argb data to the YUV420A format. The 'colorspace' // parameter is deprecated and should be equal to WEBP_YUV420. // Upon return, picture->use_argb is set to false. The presence of real // non-opaque transparent values is detected, and 'colorspace' will be // adjusted accordingly. Note that this method is lossy. // Returns false in case of error. WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture, WebPEncCSP /*colorspace = WEBP_YUV420*/); // Same as WebPPictureARGBToYUVA(), but the conversion is done using // pseudo-random dithering with a strength 'dithering' between // 0.0 (no dithering) and 1.0 (maximum dithering). This is useful // for photographic picture. WEBP_EXTERN(int) WebPPictureARGBToYUVADithered( WebPPicture* picture, WebPEncCSP colorspace, float dithering); #if WEBP_ENCODER_ABI_VERSION > 0x0204 // Performs 'smart' RGBA->YUVA420 downsampling and colorspace conversion. // Downsampling is handled with extra care in case of color clipping. This // method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better // YUV representation. // Returns false in case of error. WEBP_EXTERN(int) WebPPictureSmartARGBToYUVA(WebPPicture* picture); #endif // Converts picture->yuv to picture->argb and sets picture->use_argb to true. // The input format must be YUV_420 or YUV_420A. // Note that the use of this method is discouraged if one has access to the // raw ARGB samples, since using YUV420 is comparatively lossy. Also, the // conversion from YUV420 to ARGB incurs a small loss too. // Returns false in case of error. WEBP_EXTERN(int) WebPPictureYUVAToARGB(WebPPicture* picture); // Helper function: given a width x height plane of RGBA or YUV(A) samples // clean-up the YUV or RGB samples under fully transparent area, to help // compressibility (no guarantee, though). WEBP_EXTERN(void) WebPCleanupTransparentArea(WebPPicture* picture); // Scan the picture 'picture' for the presence of non fully opaque alpha values. // Returns true in such case. Otherwise returns false (indicating that the // alpha plane can be ignored altogether e.g.). WEBP_EXTERN(int) WebPPictureHasTransparency(const WebPPicture* picture); // Remove the transparency information (if present) by blending the color with // the background color 'background_rgb' (specified as 24bit RGB triplet). // After this call, all alpha values are reset to 0xff. WEBP_EXTERN(void) WebPBlendAlpha(WebPPicture* pic, uint32_t background_rgb); //------------------------------------------------------------------------------ // Main call // Main encoding call, after config and picture have been initialized. // 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION), // and the 'config' object must be a valid one. // Returns false in case of error, true otherwise. // In case of error, picture->error_code is updated accordingly. // 'picture' can hold the source samples in both YUV(A) or ARGB input, depending // on the value of 'picture->use_argb'. It is highly recommended to use // the former for lossy encoding, and the latter for lossless encoding // (when config.lossless is true). Automatic conversion from one format to // another is provided but they both incur some loss. WEBP_EXTERN(int) WebPEncode(const WebPConfig* config, WebPPicture* picture); //------------------------------------------------------------------------------ #ifdef __cplusplus } // extern "C" #endif #endif /* WEBP_WEBP_ENCODE_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/format_constants.h
C/C++ Header
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Internal header for constants related to WebP file format. // // Author: Urvang (urvang@google.com) #ifndef WEBP_WEBP_FORMAT_CONSTANTS_H_ #define WEBP_WEBP_FORMAT_CONSTANTS_H_ // Create fourcc of the chunk from the chunk tag characters. #define MKFOURCC(a, b, c, d) ((uint32_t)(a) | (b) << 8 | (c) << 16 | (d) << 24) // VP8 related constants. #define VP8_SIGNATURE 0x9d012a // Signature in VP8 data. #define VP8_MAX_PARTITION0_SIZE (1 << 19) // max size of mode partition #define VP8_MAX_PARTITION_SIZE (1 << 24) // max size for token partition #define VP8_FRAME_HEADER_SIZE 10 // Size of the frame header within VP8 data. // VP8L related constants. #define VP8L_SIGNATURE_SIZE 1 // VP8L signature size. #define VP8L_MAGIC_BYTE 0x2f // VP8L signature byte. #define VP8L_IMAGE_SIZE_BITS 14 // Number of bits used to store // width and height. #define VP8L_VERSION_BITS 3 // 3 bits reserved for version. #define VP8L_VERSION 0 // version 0 #define VP8L_FRAME_HEADER_SIZE 5 // Size of the VP8L frame header. #define MAX_PALETTE_SIZE 256 #define MAX_CACHE_BITS 11 #define HUFFMAN_CODES_PER_META_CODE 5 #define ARGB_BLACK 0xff000000 #define DEFAULT_CODE_LENGTH 8 #define MAX_ALLOWED_CODE_LENGTH 15 #define NUM_LITERAL_CODES 256 #define NUM_LENGTH_CODES 24 #define NUM_DISTANCE_CODES 40 #define CODE_LENGTH_CODES 19 #define MIN_HUFFMAN_BITS 2 // min number of Huffman bits #define MAX_HUFFMAN_BITS 9 // max number of Huffman bits #define TRANSFORM_PRESENT 1 // The bit to be written when next data // to be read is a transform. #define NUM_TRANSFORMS 4 // Maximum number of allowed transform // in a bitstream. typedef enum { PREDICTOR_TRANSFORM = 0, CROSS_COLOR_TRANSFORM = 1, SUBTRACT_GREEN = 2, COLOR_INDEXING_TRANSFORM = 3 } VP8LImageTransformType; // Alpha related constants. #define ALPHA_HEADER_LEN 1 #define ALPHA_NO_COMPRESSION 0 #define ALPHA_LOSSLESS_COMPRESSION 1 #define ALPHA_PREPROCESSED_LEVELS 1 // Mux related constants. #define TAG_SIZE 4 // Size of a chunk tag (e.g. "VP8L"). #define CHUNK_SIZE_BYTES 4 // Size needed to store chunk's size. #define CHUNK_HEADER_SIZE 8 // Size of a chunk header. #define RIFF_HEADER_SIZE 12 // Size of the RIFF header ("RIFFnnnnWEBP"). #define ANMF_CHUNK_SIZE 16 // Size of an ANMF chunk. #define ANIM_CHUNK_SIZE 6 // Size of an ANIM chunk. #define FRGM_CHUNK_SIZE 6 // Size of a FRGM chunk. #define VP8X_CHUNK_SIZE 10 // Size of a VP8X chunk. #define MAX_CANVAS_SIZE (1 << 24) // 24-bit max for VP8X width/height. #define MAX_IMAGE_AREA (1ULL << 32) // 32-bit max for width x height. #define MAX_LOOP_COUNT (1 << 16) // maximum value for loop-count #define MAX_DURATION (1 << 24) // maximum duration #define MAX_POSITION_OFFSET (1 << 24) // maximum frame/fragment x/y offset // Maximum chunk payload is such that adding the header and padding won't // overflow a uint32_t. #define MAX_CHUNK_PAYLOAD (~0U - CHUNK_HEADER_SIZE - 1) #endif /* WEBP_WEBP_FORMAT_CONSTANTS_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/mux.h
C/C++ Header
// Copyright 2011 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // RIFF container manipulation for WebP images. // // Authors: Urvang (urvang@google.com) // Vikas (vikasa@google.com) // This API allows manipulation of WebP container images containing features // like color profile, metadata, animation and fragmented images. // // Code Example#1: Create a WebPMux object with image data, color profile and // XMP metadata. /* int copy_data = 0; WebPMux* mux = WebPMuxNew(); // ... (Prepare image data). WebPMuxSetImage(mux, &image, copy_data); // ... (Prepare ICCP color profile data). WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data); // ... (Prepare XMP metadata). WebPMuxSetChunk(mux, "XMP ", &xmp, copy_data); // Get data from mux in WebP RIFF format. WebPMuxAssemble(mux, &output_data); WebPMuxDelete(mux); // ... (Consume output_data; e.g. write output_data.bytes to file). WebPDataClear(&output_data); */ // Code Example#2: Get image and color profile data from a WebP file. /* int copy_data = 0; // ... (Read data from file). WebPMux* mux = WebPMuxCreate(&data, copy_data); WebPMuxGetFrame(mux, 1, &image); // ... (Consume image; e.g. call WebPDecode() to decode the data). WebPMuxGetChunk(mux, "ICCP", &icc_profile); // ... (Consume icc_data). WebPMuxDelete(mux); free(data); */ #ifndef WEBP_WEBP_MUX_H_ #define WEBP_WEBP_MUX_H_ #include "./mux_types.h" #ifdef __cplusplus extern "C" { #endif #define WEBP_MUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b) // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPMuxError WebPMuxError; // typedef enum WebPChunkId WebPChunkId; typedef struct WebPMux WebPMux; // main opaque object. typedef struct WebPMuxFrameInfo WebPMuxFrameInfo; typedef struct WebPMuxAnimParams WebPMuxAnimParams; // Error codes typedef enum WebPMuxError { WEBP_MUX_OK = 1, WEBP_MUX_NOT_FOUND = 0, WEBP_MUX_INVALID_ARGUMENT = -1, WEBP_MUX_BAD_DATA = -2, WEBP_MUX_MEMORY_ERROR = -3, WEBP_MUX_NOT_ENOUGH_DATA = -4 } WebPMuxError; // IDs for different types of chunks. typedef enum WebPChunkId { WEBP_CHUNK_VP8X, // VP8X WEBP_CHUNK_ICCP, // ICCP WEBP_CHUNK_ANIM, // ANIM WEBP_CHUNK_ANMF, // ANMF WEBP_CHUNK_FRGM, // FRGM WEBP_CHUNK_ALPHA, // ALPH WEBP_CHUNK_IMAGE, // VP8/VP8L WEBP_CHUNK_EXIF, // EXIF WEBP_CHUNK_XMP, // XMP WEBP_CHUNK_UNKNOWN, // Other chunks. WEBP_CHUNK_NIL } WebPChunkId; //------------------------------------------------------------------------------ // Returns the version number of the mux library, packed in hexadecimal using // 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507. WEBP_EXTERN(int) WebPGetMuxVersion(void); //------------------------------------------------------------------------------ // Life of a Mux object // Internal, version-checked, entry point WEBP_EXTERN(WebPMux*) WebPNewInternal(int); // Creates an empty mux object. // Returns: // A pointer to the newly created empty mux object. // Or NULL in case of memory error. static WEBP_INLINE WebPMux* WebPMuxNew(void) { return WebPNewInternal(WEBP_MUX_ABI_VERSION); } // Deletes the mux object. // Parameters: // mux - (in/out) object to be deleted WEBP_EXTERN(void) WebPMuxDelete(WebPMux* mux); //------------------------------------------------------------------------------ // Mux creation. // Internal, version-checked, entry point WEBP_EXTERN(WebPMux*) WebPMuxCreateInternal(const WebPData*, int, int); // Creates a mux object from raw data given in WebP RIFF format. // Parameters: // bitstream - (in) the bitstream data in WebP RIFF format // copy_data - (in) value 1 indicates given data WILL be copied to the mux // object and value 0 indicates data will NOT be copied. // Returns: // A pointer to the mux object created from given data - on success. // NULL - In case of invalid data or memory error. static WEBP_INLINE WebPMux* WebPMuxCreate(const WebPData* bitstream, int copy_data) { return WebPMuxCreateInternal(bitstream, copy_data, WEBP_MUX_ABI_VERSION); } //------------------------------------------------------------------------------ // Non-image chunks. // Note: Only non-image related chunks should be managed through chunk APIs. // (Image related chunks are: "ANMF", "FRGM", "VP8 ", "VP8L" and "ALPH"). // To add, get and delete images, use WebPMuxSetImage(), WebPMuxPushFrame(), // WebPMuxGetFrame() and WebPMuxDeleteFrame(). // Adds a chunk with id 'fourcc' and data 'chunk_data' in the mux object. // Any existing chunk(s) with the same id will be removed. // Parameters: // mux - (in/out) object to which the chunk is to be added // fourcc - (in) a character array containing the fourcc of the given chunk; // e.g., "ICCP", "XMP ", "EXIF" etc. // chunk_data - (in) the chunk data to be added // copy_data - (in) value 1 indicates given data WILL be copied to the mux // object and value 0 indicates data will NOT be copied. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux, fourcc or chunk_data is NULL // or if fourcc corresponds to an image chunk. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxSetChunk( WebPMux* mux, const char fourcc[4], const WebPData* chunk_data, int copy_data); // Gets a reference to the data of the chunk with id 'fourcc' in the mux object. // The caller should NOT free the returned data. // Parameters: // mux - (in) object from which the chunk data is to be fetched // fourcc - (in) a character array containing the fourcc of the chunk; // e.g., "ICCP", "XMP ", "EXIF" etc. // chunk_data - (out) returned chunk data // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux, fourcc or chunk_data is NULL // or if fourcc corresponds to an image chunk. // WEBP_MUX_NOT_FOUND - If mux does not contain a chunk with the given id. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxGetChunk( const WebPMux* mux, const char fourcc[4], WebPData* chunk_data); // Deletes the chunk with the given 'fourcc' from the mux object. // Parameters: // mux - (in/out) object from which the chunk is to be deleted // fourcc - (in) a character array containing the fourcc of the chunk; // e.g., "ICCP", "XMP ", "EXIF" etc. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or fourcc is NULL // or if fourcc corresponds to an image chunk. // WEBP_MUX_NOT_FOUND - If mux does not contain a chunk with the given fourcc. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxDeleteChunk( WebPMux* mux, const char fourcc[4]); //------------------------------------------------------------------------------ // Images. // Encapsulates data about a single frame/fragment. struct WebPMuxFrameInfo { WebPData bitstream; // image data: can be a raw VP8/VP8L bitstream // or a single-image WebP file. int x_offset; // x-offset of the frame. int y_offset; // y-offset of the frame. int duration; // duration of the frame (in milliseconds). WebPChunkId id; // frame type: should be one of WEBP_CHUNK_ANMF, // WEBP_CHUNK_FRGM or WEBP_CHUNK_IMAGE WebPMuxAnimDispose dispose_method; // Disposal method for the frame. WebPMuxAnimBlend blend_method; // Blend operation for the frame. uint32_t pad[1]; // padding for later use }; // Sets the (non-animated and non-fragmented) image in the mux object. // Note: Any existing images (including frames/fragments) will be removed. // Parameters: // mux - (in/out) object in which the image is to be set // bitstream - (in) can be a raw VP8/VP8L bitstream or a single-image // WebP file (non-animated and non-fragmented) // copy_data - (in) value 1 indicates given data WILL be copied to the mux // object and value 0 indicates data will NOT be copied. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux is NULL or bitstream is NULL. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxSetImage( WebPMux* mux, const WebPData* bitstream, int copy_data); // Adds a frame at the end of the mux object. // Notes: (1) frame.id should be one of WEBP_CHUNK_ANMF or WEBP_CHUNK_FRGM // (2) For setting a non-animated non-fragmented image, use // WebPMuxSetImage() instead. // (3) Type of frame being pushed must be same as the frames in mux. // (4) As WebP only supports even offsets, any odd offset will be snapped // to an even location using: offset &= ~1 // Parameters: // mux - (in/out) object to which the frame is to be added // frame - (in) frame data. // copy_data - (in) value 1 indicates given data WILL be copied to the mux // object and value 0 indicates data will NOT be copied. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or frame is NULL // or if content of 'frame' is invalid. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxPushFrame( WebPMux* mux, const WebPMuxFrameInfo* frame, int copy_data); // Gets the nth frame from the mux object. // The content of 'frame->bitstream' is allocated using malloc(), and NOT // owned by the 'mux' object. It MUST be deallocated by the caller by calling // WebPDataClear(). // nth=0 has a special meaning - last position. // Parameters: // mux - (in) object from which the info is to be fetched // nth - (in) index of the frame in the mux object // frame - (out) data of the returned frame // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or frame is NULL. // WEBP_MUX_NOT_FOUND - if there are less than nth frames in the mux object. // WEBP_MUX_BAD_DATA - if nth frame chunk in mux is invalid. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxGetFrame( const WebPMux* mux, uint32_t nth, WebPMuxFrameInfo* frame); // Deletes a frame from the mux object. // nth=0 has a special meaning - last position. // Parameters: // mux - (in/out) object from which a frame is to be deleted // nth - (in) The position from which the frame is to be deleted // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux is NULL. // WEBP_MUX_NOT_FOUND - If there are less than nth frames in the mux object // before deletion. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxDeleteFrame(WebPMux* mux, uint32_t nth); //------------------------------------------------------------------------------ // Animation. // Animation parameters. struct WebPMuxAnimParams { uint32_t bgcolor; // Background color of the canvas stored (in MSB order) as: // Bits 00 to 07: Alpha. // Bits 08 to 15: Red. // Bits 16 to 23: Green. // Bits 24 to 31: Blue. int loop_count; // Number of times to repeat the animation [0 = infinite]. }; // Sets the animation parameters in the mux object. Any existing ANIM chunks // will be removed. // Parameters: // mux - (in/out) object in which ANIM chunk is to be set/added // params - (in) animation parameters. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or params is NULL. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxSetAnimationParams( WebPMux* mux, const WebPMuxAnimParams* params); // Gets the animation parameters from the mux object. // Parameters: // mux - (in) object from which the animation parameters to be fetched // params - (out) animation parameters extracted from the ANIM chunk // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or params is NULL. // WEBP_MUX_NOT_FOUND - if ANIM chunk is not present in mux object. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams( const WebPMux* mux, WebPMuxAnimParams* params); //------------------------------------------------------------------------------ // Misc Utilities. #if WEBP_MUX_ABI_VERSION > 0x0101 // Sets the canvas size for the mux object. The width and height can be // specified explicitly or left as zero (0, 0). // * When width and height are specified explicitly, then this frame bound is // enforced during subsequent calls to WebPMuxAssemble() and an error is // reported if any animated frame does not completely fit within the canvas. // * When unspecified (0, 0), the constructed canvas will get the frame bounds // from the bounding-box over all frames after calling WebPMuxAssemble(). // Parameters: // mux - (in) object to which the canvas size is to be set // width - (in) canvas width // height - (in) canvas height // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux is NULL; or // width or height are invalid or out of bounds // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxSetCanvasSize(WebPMux* mux, int width, int height); #endif // Gets the canvas size from the mux object. // Note: This method assumes that the VP8X chunk, if present, is up-to-date. // That is, the mux object hasn't been modified since the last call to // WebPMuxAssemble() or WebPMuxCreate(). // Parameters: // mux - (in) object from which the canvas size is to be fetched // width - (out) canvas width // height - (out) canvas height // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux, width or height is NULL. // WEBP_MUX_BAD_DATA - if VP8X/VP8/VP8L chunk or canvas size is invalid. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxGetCanvasSize(const WebPMux* mux, int* width, int* height); // Gets the feature flags from the mux object. // Note: This method assumes that the VP8X chunk, if present, is up-to-date. // That is, the mux object hasn't been modified since the last call to // WebPMuxAssemble() or WebPMuxCreate(). // Parameters: // mux - (in) object from which the features are to be fetched // flags - (out) the flags specifying which features are present in the // mux object. This will be an OR of various flag values. // Enum 'WebPFeatureFlags' can be used to test individual flag values. // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux or flags is NULL. // WEBP_MUX_BAD_DATA - if VP8X/VP8/VP8L chunk or canvas size is invalid. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxGetFeatures(const WebPMux* mux, uint32_t* flags); // Gets number of chunks with the given 'id' in the mux object. // Parameters: // mux - (in) object from which the info is to be fetched // id - (in) chunk id specifying the type of chunk // num_elements - (out) number of chunks with the given chunk id // Returns: // WEBP_MUX_INVALID_ARGUMENT - if mux, or num_elements is NULL. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxNumChunks(const WebPMux* mux, WebPChunkId id, int* num_elements); // Assembles all chunks in WebP RIFF format and returns in 'assembled_data'. // This function also validates the mux object. // Note: The content of 'assembled_data' will be ignored and overwritten. // Also, the content of 'assembled_data' is allocated using malloc(), and NOT // owned by the 'mux' object. It MUST be deallocated by the caller by calling // WebPDataClear(). It's always safe to call WebPDataClear() upon return, // even in case of error. // Parameters: // mux - (in/out) object whose chunks are to be assembled // assembled_data - (out) assembled WebP data // Returns: // WEBP_MUX_BAD_DATA - if mux object is invalid. // WEBP_MUX_INVALID_ARGUMENT - if mux or assembled_data is NULL. // WEBP_MUX_MEMORY_ERROR - on memory allocation error. // WEBP_MUX_OK - on success. WEBP_EXTERN(WebPMuxError) WebPMuxAssemble(WebPMux* mux, WebPData* assembled_data); //------------------------------------------------------------------------------ #ifdef __cplusplus } // extern "C" #endif #endif /* WEBP_WEBP_MUX_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/mux_types.h
C/C++ Header
// Copyright 2012 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Data-types common to the mux and demux libraries. // // Author: Urvang (urvang@google.com) #ifndef WEBP_WEBP_MUX_TYPES_H_ #define WEBP_WEBP_MUX_TYPES_H_ #include <stdlib.h> // free() #include <string.h> // memset() #include "./types.h" #ifdef __cplusplus extern "C" { #endif // Note: forward declaring enumerations is not allowed in (strict) C and C++, // the types are left here for reference. // typedef enum WebPFeatureFlags WebPFeatureFlags; // typedef enum WebPMuxAnimDispose WebPMuxAnimDispose; // typedef enum WebPMuxAnimBlend WebPMuxAnimBlend; typedef struct WebPData WebPData; // VP8X Feature Flags. typedef enum WebPFeatureFlags { FRAGMENTS_FLAG = 0x00000001, ANIMATION_FLAG = 0x00000002, XMP_FLAG = 0x00000004, EXIF_FLAG = 0x00000008, ALPHA_FLAG = 0x00000010, ICCP_FLAG = 0x00000020 } WebPFeatureFlags; // Dispose method (animation only). Indicates how the area used by the current // frame is to be treated before rendering the next frame on the canvas. typedef enum WebPMuxAnimDispose { WEBP_MUX_DISPOSE_NONE, // Do not dispose. WEBP_MUX_DISPOSE_BACKGROUND // Dispose to background color. } WebPMuxAnimDispose; // Blend operation (animation only). Indicates how transparent pixels of the // current frame are blended with those of the previous canvas. typedef enum WebPMuxAnimBlend { WEBP_MUX_BLEND, // Blend. WEBP_MUX_NO_BLEND // Do not blend. } WebPMuxAnimBlend; // Data type used to describe 'raw' data, e.g., chunk data // (ICC profile, metadata) and WebP compressed image data. struct WebPData { const uint8_t* bytes; size_t size; }; // Initializes the contents of the 'webp_data' object with default values. static WEBP_INLINE void WebPDataInit(WebPData* webp_data) { if (webp_data != NULL) { memset(webp_data, 0, sizeof(*webp_data)); } } // Clears the contents of the 'webp_data' object by calling free(). Does not // deallocate the object itself. static WEBP_INLINE void WebPDataClear(WebPData* webp_data) { if (webp_data != NULL) { free((void*)webp_data->bytes); WebPDataInit(webp_data); } } // Allocates necessary storage for 'dst' and copies the contents of 'src'. // Returns true on success. static WEBP_INLINE int WebPDataCopy(const WebPData* src, WebPData* dst) { if (src == NULL || dst == NULL) return 0; WebPDataInit(dst); if (src->bytes != NULL && src->size != 0) { dst->bytes = (uint8_t*)malloc(src->size); if (dst->bytes == NULL) return 0; memcpy((void*)dst->bytes, src->bytes, src->size); dst->size = src->size; } return 1; } #ifdef __cplusplus } // extern "C" #endif #endif /* WEBP_WEBP_MUX_TYPES_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/types.h
C/C++ Header
// Copyright 2010 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Common types // // Author: Skal (pascal.massimino@gmail.com) #ifndef WEBP_WEBP_TYPES_H_ #define WEBP_WEBP_TYPES_H_ #include <stddef.h> // for size_t #ifndef _MSC_VER #include <inttypes.h> #ifdef __STRICT_ANSI__ #define WEBP_INLINE #else /* __STRICT_ANSI__ */ #define WEBP_INLINE inline #endif #else typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef unsigned long long int uint64_t; typedef long long int int64_t; #define WEBP_INLINE __forceinline #endif /* _MSC_VER */ #ifndef WEBP_EXTERN // This explicitly marks library functions and allows for changing the // signature for e.g., Windows DLL builds. #define WEBP_EXTERN(type) extern type #endif /* WEBP_EXTERN */ // Macro to check ABI compatibility (same major revision number) #define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8)) #endif /* WEBP_WEBP_TYPES_H_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Tests/Tests.m
Objective-C
// // DXPhotoBrowserTests.m // DXPhotoBrowserTests // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // @import XCTest; @interface Tests : XCTestCase @end @implementation Tests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__); } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXErrorIndicator.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface DXErrorIndicator : UIButton @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXErrorIndicator.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXErrorIndicator.h" #import "DXShapeImageLayer.h" @implementation DXErrorIndicator - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { DXCrossLayer *cross = [DXCrossLayer new]; cross.bounds = self.bounds; [self setImage:cross.normalImage forState:UIControlStateNormal]; } return self; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXPhoto.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @protocol DXPhoto <NSObject> typedef void (^DXPhotoProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); typedef void (^DXPhotoCompletionBlock)(id<DXPhoto>, UIImage *image); @required - (void)loadImageWithProgressBlock:(DXPhotoProgressBlock)progressBlock completionBlock:(DXPhotoCompletionBlock)completionBlock; @optional - (UIImage *)placeholder; - (void)cancelLoadImage; /** * Uses animation for expand and shrink, if not provide default is screenBounds. * Uses pixels size instead of point * * @return an expectLoadedImageSize; */ - (CGSize)expectLoadedImageSize; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXPhotoBrowser.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <Foundation/Foundation.h> #import "DXPhoto.h" @protocol DXPhotoBrowserDelegate; @class DXPullToDetailView; @interface DXPhotoBrowser : NSObject /** * Desigated intializer * * @param photosArray an array of id<DXPhoto> * */ - (instancetype)initWithPhotosArray:(NSArray *)photosArray; @property (nonatomic, strong, readonly) NSArray *photosArray; // if you imp the delegate method "simplePhotoBrowserDidTriggerPullToRightEnd:", then maybe you need to set the text @property (nonatomic, strong, readonly) DXPullToDetailView *pullToRightControl; // if current photos.count > 10, it will hidden @property (nonatomic, strong, readonly) UIPageControl *pageControl; @property (nonatomic, weak) id<DXPhotoBrowserDelegate> delegate; @property (nonatomic, assign, getter=isBouncingAnimation) BOOL bouncingAnimation; /** * The showing photo api * * @param index the index of within the photosArray * @param thumbnailView the animation from view, if set to nil, it will display without the expand animation */ - (void)showPhotoAtIndex:(NSUInteger)index withThumbnailImageView:(UIView *)thumbnailView; - (void)hide; @end @protocol DXPhotoBrowserDelegate <NSObject> @optional /** * * 如果要改变当前statusBarStyle的话, 这些delegate可以用到。 * 记得在info.plist里添加`UIViewControllerBasedStatusBarAppearance == NO` * */ - (void)simplePhotoBrowserWillShow:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidShow:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserWillHide:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidHide:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidTriggerPullToRightEnd:(DXPhotoBrowser *)photoBrowser; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXPhotoBrowser.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXPhotoBrowser.h" #import "UIView+DXScreenShot.h" #import "UIImage+DXAppleBlur.h" #import "DXPullToDetailView.h" #import "DXZoomingScrollView.h" #import "DXTapDetectingImageView.h" #import "DXTapDetectingView.h" static const CGFloat kPadding = 10.0; static inline NSTimeInterval durationToAnimate(CGFloat pointsToAnimate, CGFloat velocity) { NSTimeInterval animationDuration = pointsToAnimate / ABS(velocity); return animationDuration; } static inline CGSize screenRatioSize(CGSize fullScreenSize, CGSize originViewSize) { CGFloat x, X, y, Y, rx, ry; x = originViewSize.width, X = fullScreenSize.width; y = originViewSize.height, Y = fullScreenSize.height; if (x == 0 || y == 0) { return CGSizeZero; } // we use the bigger ratio if (x / X > y / Y) { rx = X; ry = X / x * y; } else { ry = Y; rx = Y / y * x; } if (x <= X) { rx = x; if (y <= Y) { ry = y; } else { ry = rx / x * y; } } return CGSizeMake(rx, ry); } @interface DXPhotoBrowser ()<UIScrollViewDelegate, DXZoomingScrollViewDelegate> @property (nonatomic, weak) UIView *sourceView; @property (nonatomic, strong, readonly) UIView *fullcreenView; @property (nonatomic, strong, readonly) UIControl *backgroundView; // if current photos.count > 10, it will hidden @property (nonatomic, strong) UIPageControl *pageControl; /** * Default is 0.3 */ @property (nonatomic, assign) CGFloat flyInAnimationDuration; /** * Default is 0.3 */ @property (nonatomic, assign) CGFloat flyOutAnimationDuration; @end @implementation DXPhotoBrowser { UIView *_fullscreenView; UIControl *_backgroundView; UIScrollView *_pagingScrollView; NSMutableSet *_visiblePages, *_recycledPages; NSUInteger _currentPageIndex; NSUInteger _photoCount; DXPullToDetailView *_pullToRightControl; UIPanGestureRecognizer *_dismissPanGesture; NSArray *_photosArray; CGRect _sourceViewHereFrame; CGFloat _startShowingIndex; BOOL _isiOS7; struct { unsigned int delegateImpWillShowObj:1; unsigned int delegateImpDidShowObj:1; unsigned int delegateImpWillHideObj:1; unsigned int delegateImpDidHideObj:1; unsigned int delegateImpTriggerPullToRight:1; } _delegateFlags; UIImage *_fakeAnimationPlaceholder; UIImageView *_fakeAnimationImageView; } @synthesize fullcreenView = _fullscreenView, backgroundView = _backgroundView; #pragma -mark lifecycle - (void)dealloc { [_fullscreenView removeFromSuperview]; [_backgroundView removeFromSuperview]; _delegate = nil; } - (instancetype)init { NSAssert(NO, @"Please use initWithPhotosArray: instead"); return nil; } - (void)commonInit { UIViewAutoresizing autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); self.flyInAnimationDuration = 0.3; self.flyOutAnimationDuration = 0.3; self.bouncingAnimation = YES; _isiOS7 = [[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending; _fullscreenView = [[UIView alloc] init]; [_fullscreenView setAutoresizingMask:autoresizingMask]; _backgroundView = [[UIControl alloc] init]; [_backgroundView setAutoresizingMask:autoresizingMask]; [_backgroundView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.8]]; [_backgroundView addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside]; CGRect pagingScrollViewFrame = [self frameForPagingScrollView]; _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame]; _pagingScrollView.autoresizingMask = autoresizingMask; _pagingScrollView.pagingEnabled = YES; _pagingScrollView.delegate = self; _pagingScrollView.showsHorizontalScrollIndicator = NO; _pagingScrollView.showsVerticalScrollIndicator = NO; _pagingScrollView.backgroundColor = [UIColor clearColor]; _pagingScrollView.contentSize = [self contentSizeForPagingScrollView]; _pullToRightControl = [[DXPullToDetailView alloc] initWithFrame:_pagingScrollView.bounds]; _pullToRightControl.releasingText = @"请配置释放文案"; _pullToRightControl.pullingText = @"请配置滑动文案"; _pageControl = [[UIPageControl alloc] init]; _pageControl.userInteractionEnabled = NO; //recycle staff _visiblePages = [[NSMutableSet alloc] init]; _recycledPages = [[NSMutableSet alloc] init]; _photoCount = NSNotFound; _currentPageIndex = 0; _dismissPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; _dismissPanGesture.maximumNumberOfTouches = 1; _dismissPanGesture.minimumNumberOfTouches = 1; _delegateFlags.delegateImpWillShowObj = 0; _delegateFlags.delegateImpDidShowObj = 0; _delegateFlags.delegateImpWillHideObj = 0; _delegateFlags.delegateImpDidHideObj = 0; _delegateFlags.delegateImpTriggerPullToRight = 0; } - (instancetype)initWithPhotosArray:(NSArray *)photosArray { if (self = [super init]) { [self commonInit]; _photosArray = photosArray; } return self; } - (void)setDelegate:(id<DXPhotoBrowserDelegate>)delegate { if (_delegate != delegate) { _delegateFlags.delegateImpWillShowObj = [delegate respondsToSelector:@selector(simplePhotoBrowserWillShow:)]; _delegateFlags.delegateImpDidShowObj = [delegate respondsToSelector:@selector(simplePhotoBrowserDidShow:)]; _delegateFlags.delegateImpWillHideObj = [delegate respondsToSelector:@selector(simplePhotoBrowserWillHide:)]; _delegateFlags.delegateImpDidHideObj = [delegate respondsToSelector:@selector(simplePhotoBrowserDidHide:)]; _delegateFlags.delegateImpTriggerPullToRight = [delegate respondsToSelector:@selector(simplePhotoBrowserDidTriggerPullToRightEnd:)]; _delegate = delegate; } } #pragma -mark scrollView events - (CGRect)frameForPagingScrollView { CGRect frame = [_fullscreenView bounds]; frame.origin.x -= kPadding; frame.size.width += (2 * kPadding); return CGRectIntegral(frame); } - (CGSize)contentSizeForPagingScrollView { // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above. CGRect bounds = _pagingScrollView.bounds; return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height); } - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index { CGFloat pageWidth = _pagingScrollView.bounds.size.width; CGFloat newOffset = index * pageWidth; return CGPointMake(newOffset, 0); } - (CGRect)frameForPageAtIndex:(NSUInteger)index { // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape // because it has a rotation transform applied. CGRect bounds = _pagingScrollView.bounds; CGRect pageFrame = bounds; pageFrame.size.width -= (2 * kPadding); pageFrame.origin.x = (bounds.size.width * index) + kPadding; return CGRectIntegral(pageFrame); } - (NSUInteger)numberOfPhotos { return _photosArray.count; } - (void)resetPagingScrollView { // Reset _photoCount = NSNotFound; // Get data NSUInteger numberOfPhotos = [self numberOfPhotos]; // Update current page index if (numberOfPhotos > 0) { _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1)); } else { _currentPageIndex = 0; } // Update layout while (_pagingScrollView.subviews.count) { [[_pagingScrollView.subviews lastObject] removeFromSuperview]; } // Setup pages [_visiblePages removeAllObjects]; [_recycledPages removeAllObjects]; _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex]; [_pagingScrollView setFrame:[self frameForPagingScrollView]]; [_pagingScrollView setContentSize:[self contentSizeForPagingScrollView]]; [_pagingScrollView setAlpha:0.0]; _pagingScrollView.delegate = self; } - (void)tilePages { // Calculate which pages should be visible // Ignore padding as paging bounces encroach on that // and lead to false page loads CGRect visibleBounds = _pagingScrollView.bounds; NSInteger firstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds) + kPadding * 2) / CGRectGetWidth(visibleBounds)); NSInteger lastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds) - kPadding * 2 - 1) / CGRectGetWidth(visibleBounds)); if (firstIndex < 0) firstIndex = 0; if (firstIndex > [self numberOfPhotos] - 1) firstIndex = [self numberOfPhotos] - 1; if (lastIndex < 0) lastIndex = 0; if (lastIndex > [self numberOfPhotos] - 1) lastIndex = [self numberOfPhotos] - 1; // Recycle no longer needed pages NSInteger pageIndex; for (DXZoomingScrollView *page in _visiblePages) { pageIndex = page.index; if (pageIndex < firstIndex || pageIndex > lastIndex) { [_recycledPages addObject:page]; [page prepareForReuse]; [page removeFromSuperview]; } } [_visiblePages minusSet:_recycledPages]; while (_recycledPages.count > 3) // Only keep 3 recycled pages [_recycledPages removeObject:[_recycledPages anyObject]]; // Add missing pages for (NSUInteger index = firstIndex; index <= lastIndex; index++) { if (![self isDisplayingPageForIndex:index]) { // Add new page DXZoomingScrollView *page = [self dequeueRecycledPage]; if (!page) { page = [[DXZoomingScrollView alloc] initWithDelegate:self]; } [_visiblePages addObject:page]; [self configurePage:page forIndex:index]; [_pagingScrollView addSubview:page]; } } } - (BOOL)isDisplayingPageForIndex:(NSUInteger)index { for (DXZoomingScrollView *page in _visiblePages) if (page.index == index) return YES; return NO; } - (DXZoomingScrollView *)dequeueRecycledPage { DXZoomingScrollView *page = [_recycledPages anyObject]; if (page) { [_recycledPages removeObject:page]; } return page; } - (void)configurePage:(DXZoomingScrollView *)page forIndex:(NSUInteger)index { page.frame = [self frameForPageAtIndex:index]; page.index = index; if (index == _startShowingIndex) { id<DXPhoto> photo = [self photoAtIndex:index]; UIImage *placeholder = [photo respondsToSelector:@selector(placeholder)] ? [photo placeholder] : nil; if (!placeholder && _fakeAnimationPlaceholder) { placeholder = _fakeAnimationPlaceholder; page.placeholder = placeholder; } } page.photo = [self photoAtIndex:index]; } - (id<DXPhoto>)photoAtIndex:(NSUInteger)index { id<DXPhoto> cellObj = nil; if (index < _photosArray.count) { cellObj = _photosArray[index]; } if (![cellObj conformsToProtocol:@protocol(DXPhoto)]) { NSLog(@"DXPhotoBrowser photos array object at index %lu does conforms to protocol <HRPhoto>", (unsigned long)index); return nil; } return cellObj; } - (DXZoomingScrollView *)pageAtIndex:(NSUInteger)index { for (DXZoomingScrollView *page in _visiblePages) { if (page.index == _currentPageIndex) { return page; } } return nil; } - (BOOL)isSatisfiedJumpWithScrollView:(UIScrollView *)scrollView { BOOL satisfy = (scrollView.contentOffset.x + CGRectGetWidth(scrollView.bounds) - scrollView.contentSize.width > 60.0); return satisfy; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self tilePages]; CGRect visibleBounds = _pagingScrollView.bounds; NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))); if (index < 0) index = 0; if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1; _currentPageIndex = index; _pageControl.currentPage = _currentPageIndex; // moved 60.0 if ([self isSatisfiedJumpWithScrollView:scrollView]) { if (scrollView.isDragging == YES) { [_pullToRightControl setPulling:YES animated:YES]; }else { // iOS6 当pageEnabled == YES的时候无法判断速度, 这里降级处理 if (!_isiOS7) { if (_delegateFlags.delegateImpTriggerPullToRight) { [self hideAnimated:NO]; scrollView.delegate = nil; [self.delegate simplePhotoBrowserDidTriggerPullToRightEnd:self]; } } } }else { [_pullToRightControl setPulling:NO animated:YES]; } } - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { if ([self isSatisfiedJumpWithScrollView:scrollView]) { if (velocity.x < 1.0) { if (_delegateFlags.delegateImpTriggerPullToRight) { [self hideAnimated:NO]; scrollView.delegate = nil; [self.delegate simplePhotoBrowserDidTriggerPullToRightEnd:self]; } } } } - (void)tilePagesAtIndex:(NSUInteger)index { CGRect bounds = _pagingScrollView.bounds; bounds.origin.x = [self contentOffsetForPageAtIndex:index].x; _pagingScrollView.bounds = bounds; _currentPageIndex = index; _pageControl.numberOfPages = [self numberOfPhotos]; _pageControl.currentPage = _currentPageIndex; _pageControl.hidden = _pageControl.numberOfPages <= 1; [_pageControl sizeToFit]; CGPoint pageCenter = _pagingScrollView.center; pageCenter.y = CGRectGetHeight(_pagingScrollView.bounds) - CGRectGetHeight(_pageControl.bounds); _pageControl.center = pageCenter; [self tilePages]; } - (void)handlePan:(id)sender { // Initial Setup DXZoomingScrollView *scrollView = [self pageAtIndex:_currentPageIndex]; static CGFloat firstX, firstY; CGFloat viewHeight = scrollView.frame.size.height; CGFloat viewHalfHeight = viewHeight / 2; CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:_fullscreenView ]; CGPoint velocity = [(UIPanGestureRecognizer*)sender velocityInView:_fullscreenView]; // Gesture Began if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { firstX = [scrollView center].x; firstY = [scrollView center].y; } translatedPoint = CGPointMake(firstX, firstY+translatedPoint.y); [scrollView setCenter:translatedPoint]; CGFloat newY = scrollView.center.y - viewHalfHeight; CGFloat newAlpha = 1 - ABS(newY) / viewHeight; _backgroundView.opaque = YES; _backgroundView.alpha = newAlpha; // Gesture Ended if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) { CGFloat autoDismissOffset = 50.0; // if moved > autoDismissOffset if (scrollView.center.y > viewHalfHeight + autoDismissOffset || scrollView.center.y < viewHalfHeight - autoDismissOffset) { if (_sourceView && _currentPageIndex == _startShowingIndex) { [self hide]; return; } CGFloat finalX = firstX, finalY; CGFloat windowsHeigt = _fullscreenView.bounds.size.height; if(scrollView.center.y > viewHalfHeight + 30) // swipe down finalY = windowsHeigt * 2; else // swipe up finalY = -viewHalfHeight; CGFloat animationDuration = durationToAnimate(windowsHeigt * 0.5, ABS(velocity.y)); if (animationDuration < 0.1) animationDuration = 0.1; if (animationDuration > 0.35) animationDuration = 0.35; [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^ { [scrollView setCenter:CGPointMake(finalX, finalY)]; } completion:NULL]; [self performSelector:@selector(hide) withObject:self afterDelay:animationDuration]; } else { // continue show part CGFloat velocityY = (.35 * velocity.y); CGFloat finalX = firstX; CGFloat finalY = viewHalfHeight; CGFloat animationDuration = (ABS(velocityY) * 0.0002)+ 0.2; [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^ { [scrollView setCenter:CGPointMake(finalX, finalY)]; _backgroundView.alpha = 1.0; } completion:NULL]; } } } #pragma -mark show & hide - (void)showPhotoAtIndex:(NSUInteger)index withThumbnailImageView:(UIView *)thumbnailView { if (index > _photosArray.count) { NSLog(@"Expected showing photo index %lu is out of range with total photos count %lu and current index", (unsigned long)index, (unsigned long)_photosArray.count); index = 0; } if (!_photosArray || _photosArray.count == 0) return; _startShowingIndex = index; // setup the root view UIView *rootViewControllerView = [[UIApplication sharedApplication] keyWindow].rootViewController.view; [_fullscreenView setFrame:[rootViewControllerView bounds]]; [rootViewControllerView addSubview:_fullscreenView]; [_fullscreenView addGestureRecognizer:_dismissPanGesture]; // Stash away original thumbnail image view information if (thumbnailView) { _sourceView = thumbnailView; _sourceViewHereFrame = [_sourceView.superview convertRect:_sourceView.frame toView:_fullscreenView]; _sourceView.hidden = YES; } // Configure the background view, iOS6的截图效率太低,这里使用半透明黑色背景替代 UIColor *backgroundColor; if (_isiOS7) { UIImage *screenShotImage = [rootViewControllerView dx_screenShotImageAfterScreenUpdates:NO]; screenShotImage = [screenShotImage dx_applyBlackEffect]; backgroundColor = [UIColor colorWithPatternImage:screenShotImage]; }else { backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7]; } _backgroundView.backgroundColor = backgroundColor; [_backgroundView setFrame:[_fullscreenView bounds]]; [_backgroundView setAlpha:0]; [_fullscreenView addSubview:_backgroundView]; // reset the page scrollView [self resetPagingScrollView]; CGRect finalFakeAnimationRect = [self createFakeAnimationImageViewIfNeed]; [self tilePagesAtIndex:index]; [_fullscreenView addSubview:_pagingScrollView]; // pullToDetailView if (_delegateFlags.delegateImpTriggerPullToRight) { _pullToRightControl.frame = CGRectMake((_pagingScrollView.contentSize.width), 0, 44.0, CGRectGetHeight(_pagingScrollView.bounds)); [_pagingScrollView addSubview:_pullToRightControl]; } else { [_pullToRightControl removeFromSuperview]; } // pagecontrol _pageControl.hidden = _photosArray.count > 10; [self performAnimateFlyInWithFakeAnimationImageViewDestinationRect:finalFakeAnimationRect]; } - (CGRect)createFakeAnimationImageViewIfNeed { if (!_sourceView) return CGRectZero; UIImage *scaleImage; id<DXPhoto> startPhoto = [self photoAtIndex:_startShowingIndex]; if ([startPhoto respondsToSelector:@selector(placeholder)]) { scaleImage = [startPhoto placeholder]; } if (!scaleImage) { scaleImage = [_sourceView dx_screenShotImageAfterScreenUpdates:NO]; } // The destination imageSize, if the image has loaded we use it CGSize imageSize = CGSizeZero; if ([startPhoto respondsToSelector:@selector(expectLoadedImageSize)]) { imageSize = [startPhoto expectLoadedImageSize]; imageSize = screenRatioSize(_fullscreenView.bounds.size, imageSize); } // last solution we use the screen size if (CGSizeEqualToSize(imageSize, CGSizeZero) && _sourceView) { imageSize = screenRatioSize(_fullscreenView.bounds.size, _sourceView.bounds.size); } CGRect screenBound = CGRectMake(0, 0, imageSize.width, imageSize.height); UIImageView *resizableImageView; CGRect finalImageViewFrame; if (!CGSizeEqualToSize(screenBound.size, CGSizeZero) && _sourceView) { CGFloat screenWidth = screenBound.size.width; CGFloat screenHeight = screenBound.size.height; resizableImageView = [[UIImageView alloc] initWithImage:scaleImage]; resizableImageView.frame = _sourceViewHereFrame; resizableImageView.clipsToBounds = YES; resizableImageView.contentMode = UIViewContentModeScaleAspectFill; [_fullscreenView addSubview:resizableImageView]; finalImageViewFrame = CGRectMake((CGRectGetWidth(_fullscreenView.bounds) - screenWidth) * 0.5, (CGRectGetHeight(_fullscreenView.bounds) - screenHeight) * 0.5, screenWidth, screenHeight); UIImage *placeholder = [startPhoto respondsToSelector:@selector(placeholder)] ? [startPhoto placeholder] : nil; if (!placeholder) { UIImageView *imageForDest = [[UIImageView alloc] initWithFrame:finalImageViewFrame]; imageForDest.image = scaleImage; imageForDest.clipsToBounds = YES; imageForDest.contentMode = UIViewContentModeScaleAspectFill; _fakeAnimationPlaceholder = [imageForDest dx_screenShotImageAfterScreenUpdates:YES]; } } _fakeAnimationImageView = resizableImageView; return finalImageViewFrame; } - (void)performAnimateFlyInWithFakeAnimationImageViewDestinationRect:(CGRect)destRect { if (_delegateFlags.delegateImpWillShowObj) { [_delegate simplePhotoBrowserWillShow:self]; } dispatch_block_t animation = ^{ [_backgroundView setAlpha:1.0]; if (_fakeAnimationImageView) { _fakeAnimationImageView.layer.frame = destRect; } else { [_pagingScrollView setAlpha:1.0]; } }; dispatch_block_t completion = ^{ [_fakeAnimationImageView removeFromSuperview]; _fakeAnimationImageView = nil; _fakeAnimationPlaceholder = nil; [_pagingScrollView setAlpha:1.0]; if (_delegateFlags.delegateImpDidShowObj) { [_delegate simplePhotoBrowserDidShow:self]; } }; if (self.isBouncingAnimation && _isiOS7) { [UIView animateWithDuration:self.flyInAnimationDuration + 0.1 delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:6.0 options:UIViewAnimationOptionCurveEaseIn animations:animation completion:^(BOOL finished) { completion(); }]; }else { [UIView animateWithDuration:self.flyInAnimationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:animation completion:^(BOOL finished) { completion(); }]; } } - (void)hide { [self hideAnimated:YES]; } - (BOOL)shouldAnimateSourceViewFrame { return _sourceView && _currentPageIndex == _startShowingIndex; } - (void)hideAnimated:(BOOL)animated { CGFloat duration = 0.0; if (animated) duration = self.flyOutAnimationDuration; if ([self shouldAnimateSourceViewFrame] && duration > 0) { DXZoomingScrollView *scrollView = [self pageAtIndex:_currentPageIndex]; [self performHideAnimatioWithScrollView:scrollView withDuration:duration]; }else { _sourceView.hidden = NO; } [_pagingScrollView setAlpha:0.0]; [UIView animateWithDuration:duration animations:^{ [_backgroundView setAlpha:0]; } completion:^(BOOL finished) { _sourceView.hidden = NO; [_pageControl removeFromSuperview]; [_pagingScrollView removeFromSuperview]; [_backgroundView removeFromSuperview]; [_fullscreenView removeFromSuperview]; _pagingScrollView.alpha = 1.0; _pagingScrollView.transform = CGAffineTransformIdentity; [_fullscreenView removeGestureRecognizer:_dismissPanGesture]; // Inform the delegate that we just hide a fullscreen photo if (_delegateFlags.delegateImpDidHideObj) { [_delegate simplePhotoBrowserDidHide:self]; } }]; } - (void)performHideAnimatioWithScrollView:(DXZoomingScrollView *)scrollView withDuration:(CGFloat)duration { UIImage *imageFromView = nil; if ([scrollView.photo respondsToSelector:@selector(placeholder)]) { imageFromView = [scrollView.photo placeholder]; } if (!imageFromView) { imageFromView = [scrollView placeholder]; } CGRect screenBound = [[[self pageAtIndex:_currentPageIndex] imageView] frame]; UIImageView *resizableImageView; if (!CGSizeEqualToSize(screenBound.size, CGSizeZero)) { screenBound = [scrollView convertRect:screenBound toView:_fullscreenView]; resizableImageView = [[UIImageView alloc] initWithImage:imageFromView]; resizableImageView.frame = screenBound; resizableImageView.contentMode = UIViewContentModeScaleAspectFill; resizableImageView.backgroundColor = [UIColor clearColor]; resizableImageView.clipsToBounds = YES; [_fullscreenView addSubview:resizableImageView]; } dispatch_block_t animation = ^{ resizableImageView.layer.frame = _sourceViewHereFrame; }; dispatch_block_t completion = ^{ [resizableImageView removeFromSuperview]; }; if (self.isBouncingAnimation && _isiOS7) { [UIView animateWithDuration:duration + 0.1 delay:0.0 usingSpringWithDamping:0.9 initialSpringVelocity:4.0 options:UIViewAnimationOptionCurveEaseOut animations:animation completion:^(BOOL finished) { completion(); }]; }else { [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:animation completion:^(BOOL finished) { completion(); }]; } } - (void)zoomingScrollViewSingleTapped:(DXZoomingScrollView *)zoomingScrollView { [self hide]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXPullToDetailView.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface DXPullToDetailView : UIView @property (nonatomic, assign) BOOL pulling; @property (nonatomic, strong) NSString *pullingText; @property (nonatomic, strong) NSString *releasingText; @property (nonatomic, strong, readonly) UILabel *textLabel; - (void)setPulling:(BOOL)pulling animated:(BOOL)animated; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXPullToDetailView.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXPullToDetailView.h" #import "DXShapeImageLayer.h" @implementation DXPullToDetailView { UIImageView *_arrow; UILabel *_textLabel; } - (instancetype)initWithFrame:(CGRect)frame { frame.size.width = 200.0; self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; _arrow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20.0, 20.0)]; _arrow.center = CGPointMake(15.0, CGRectGetMidY(self.bounds)); UIImage *previewImage = [UIImage imageNamed:@"preview_indicator"]; if (!previewImage) { DXArrowLayer *arrowLayer = [DXArrowLayer new]; arrowLayer.bounds = _arrow.bounds; previewImage = [arrowLayer normalImage]; } _arrow.image = previewImage; [self addSubview:_arrow]; _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_arrow.frame) + 10.0, 0.0, 15.0, CGRectGetHeight(self.bounds))]; _textLabel.numberOfLines = 0.0; _textLabel.lineBreakMode = NSLineBreakByWordWrapping; _textLabel.textAlignment = NSTextAlignmentCenter; _textLabel.textColor = [UIColor whiteColor]; _textLabel.backgroundColor = [UIColor clearColor]; _textLabel.font = [UIFont systemFontOfSize:CGRectGetWidth(_textLabel.frame) - 1.0]; [self addSubview:_textLabel]; } return self; } - (void)setPulling:(BOOL)pulling animated:(BOOL)animated { CGFloat duration = animated ? 0.2 : 0.0; if (_pulling != pulling) { if (pulling) { [UIView animateWithDuration:duration animations:^{ _arrow.transform = CGAffineTransformMakeRotation((M_PI)); }]; _textLabel.text = _releasingText; } else { [UIView animateWithDuration:duration animations:^{ _arrow.transform = CGAffineTransformIdentity; }]; _textLabel.text = _pullingText; } _pulling = pulling; } } - (void)setPulling:(BOOL)pulling { [self setPulling:pulling animated:NO]; } - (void)willMoveToWindow:(UIWindow *)newWindow { [super willMoveToWindow:newWindow]; if (newWindow) { _arrow.transform = CGAffineTransformIdentity; _textLabel.text = _pullingText; } } - (void)layoutSubviews { [super layoutSubviews]; _arrow.center = CGPointMake(15.0, CGRectGetMidY(self.bounds)); _textLabel.frame = CGRectMake(CGRectGetMaxX(_arrow.frame) + 10.0, 0.0, 15.0, CGRectGetHeight(self.bounds)); } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXShapeImageLayer.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <QuartzCore/QuartzCore.h> @interface DXShapeImageLayer : CALayer @property (nonatomic, strong) UIColor *normalColor; @property (nonatomic, strong) UIColor *highlightedColor; /** * This shape which maded by this cells. * When subclass, remember to add you cells into this array */ @property (nonatomic, strong) NSMutableArray *cellLayers; - (UIImage *)normalImage; - (UIImage *)highlightedImage; @end @interface DXCrossLayer : DXShapeImageLayer /** * Default is 1.0 */ @property (nonatomic, assign) CGFloat crossLineWidth; /** * Use 45.0, 90.0 instead of PI */ @property (nonatomic, assign) CGFloat crossLineAngle; /** * Default is 1.0 */ @property (nonatomic, assign) CGFloat crossLineCornerRadius; @end @interface DXArrowLayer : DXShapeImageLayer /** * default is 1.0 */ @property (nonatomic, assign) CGFloat lineWidth; /** * default is 1.0 */ @property (nonatomic, assign) CGFloat circleLineWidth; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXShapeImageLayer.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #define dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(layer, nowAnchorPoint) \ CGPoint dx_lastAnchor = layer.anchorPoint;\ layer.anchorPoint = nowAnchorPoint;\ layer.position \ = CGPointMake(layer.position.x+(nowAnchorPoint.x-dx_lastAnchor.x)*layer.bounds.size.width, \ layer.position.y+(nowAnchorPoint.y-dx_lastAnchor.y)*layer.bounds.size.height);\ static inline CGFloat radians(CGFloat degrees) { return ( degrees * M_PI ) / 180.0; } #import "DXShapeImageLayer.h" @implementation DXShapeImageLayer - (instancetype)init { self = [super init]; if (self) { _normalColor = [UIColor whiteColor]; _highlightedColor = [UIColor darkGrayColor]; _cellLayers = [NSMutableArray array]; } return self; } - (UIImage *)normalImage { for (CALayer *layer in self.cellLayers) { layer.backgroundColor = self.normalColor.CGColor; } return [self toImage]; } - (UIImage *)highlightedImage { for (CALayer *layer in self.cellLayers) { layer.backgroundColor = self.highlightedColor.CGColor; } return [self toImage]; } - (UIImage *)toImage { CGSize size = self.bounds.size; if (CGSizeEqualToSize(size, CGSizeZero)) return nil; CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height); UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClearRect(context, rect); [self renderInContext:context]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end @implementation DXCrossLayer { CALayer *_left; CALayer *_right; } - (instancetype)init { self = [super init]; if (self) { self.crossLineAngle = radians(45.0); self.crossLineWidth = 1.0; self.crossLineCornerRadius = 1.0; _left = [CALayer layer]; _right = [CALayer layer]; [self addSublayer:_left]; [self addSublayer:_right]; [self.cellLayers addObject:_left]; [self.cellLayers addObject:_right]; } return self; } - (void)setBounds:(CGRect)bounds { if (!CGRectEqualToRect(bounds, self.bounds)) { CGRect crossFrame = CGRectInset(bounds, (CGRectGetWidth(bounds) - self.crossLineWidth) * 0.5, 0.0); _left.frame = crossFrame; _right.frame = crossFrame; _left.transform = CATransform3DMakeRotation(-self.crossLineAngle, 0.0, 0.0, 1.0); _right.transform = CATransform3DMakeRotation(self.crossLineAngle, 0.0, 0.0, 1.0); [self setNeedsDisplay]; } [super setBounds:bounds]; } @end @implementation DXArrowLayer { CAShapeLayer *_circle; CALayer *_middleLine; CALayer *_upLine; CALayer *_downLine; } - (instancetype)init { self = [super init]; if (self) { _lineWidth = 1.0; _circleLineWidth = 1.0; self.masksToBounds = NO; _circle = [CAShapeLayer new]; _middleLine = [CALayer layer]; _upLine = [CALayer layer]; _downLine = [CALayer layer]; [self addSublayer:_circle]; [self addSublayer:_middleLine]; [self addSublayer:_upLine]; [self addSublayer:_downLine]; [self.cellLayers addObject:_circle]; [self.cellLayers addObject:_middleLine]; [self.cellLayers addObject:_upLine]; [self.cellLayers addObject:_downLine]; } return self; } - (void)setBounds:(CGRect)bounds { if (!CGRectEqualToRect(bounds, self.bounds)) { _circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(bounds, 1.0, 1.0) cornerRadius:CGRectGetMidX(bounds)].CGPath; _circle.lineWidth = _circleLineWidth; _circle.fillColor = [UIColor clearColor].CGColor; _circle.strokeColor = self.normalColor.CGColor; CGFloat middleLineWidth = bounds.size.width * 0.5; _middleLine.frame = CGRectMake((CGRectGetWidth(bounds) - middleLineWidth) * 0.5 , (CGRectGetHeight(bounds) - _lineWidth) * 0.5, middleLineWidth, _lineWidth); [self addSublayer:_middleLine]; [self setupUpLine]; [self setupDownLine]; [self setNeedsDisplay]; } [super setBounds:bounds]; } - (void)setupUpLine { _upLine.frame = CGRectMake(CGRectGetMinX(_middleLine.frame), CGRectGetMinY(_middleLine.frame), CGRectGetWidth(_middleLine.frame) * 0.5, _lineWidth); _upLine.transform = CATransform3DMakeRotation(-radians(40.0), 0.0, 0.0, 1.0); dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(_upLine, CGPointMake(0.0, 0.5)); [self addSublayer:_upLine]; } - (void)setupDownLine { _downLine.frame = CGRectMake(CGRectGetMinX(_middleLine.frame), CGRectGetMinY(_middleLine.frame), CGRectGetWidth(_middleLine.frame) * 0.5, _lineWidth); _downLine.transform = CATransform3DMakeRotation(radians(40.0), 0.0, 0.0, 1.0); dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(_downLine, CGPointMake(0.0, 0.5)); [self addSublayer:_downLine]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXTapDetectingImageView.h
C/C++ Header
// // UIImageViewTap.h // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import <Foundation/Foundation.h> @protocol DXTapDetectingImageViewDelegate; @interface DXTapDetectingImageView : UIImageView {} @property (nonatomic, weak) id <DXTapDetectingImageViewDelegate> tapDelegate; @end @protocol DXTapDetectingImageViewDelegate <NSObject> @optional - (void)imageView:(UIImageView *)imageView singleTapDetected:(UITouch *)touch; - (void)imageView:(UIImageView *)imageView doubleTapDetected:(UITouch *)touch; - (void)imageView:(UIImageView *)imageView tripleTapDetected:(UITouch *)touch; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXTapDetectingImageView.m
Objective-C
// // UIImageViewTap.m // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import "DXTapDetectingImageView.h" @implementation DXTapDetectingImageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithImage:(UIImage *)image { if ((self = [super initWithImage:image])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage { if ((self = [super initWithImage:image highlightedImage:highlightedImage])) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; NSUInteger tapCount = touch.tapCount; switch (tapCount) { case 1: [self handleSingleTap:touch]; break; case 2: [self handleDoubleTap:touch]; break; case 3: [self handleTripleTap:touch]; break; default: break; } [[self nextResponder] touchesEnded:touches withEvent:event]; } - (void)handleSingleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:singleTapDetected:)]) [_tapDelegate imageView:self singleTapDetected:touch]; } - (void)handleDoubleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:doubleTapDetected:)]) [_tapDelegate imageView:self doubleTapDetected:touch]; } - (void)handleTripleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:tripleTapDetected:)]) [_tapDelegate imageView:self tripleTapDetected:touch]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXTapDetectingView.h
C/C++ Header
// // UIViewTap.h // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import <Foundation/Foundation.h> @protocol DXTapDetectingViewDelegate; @interface DXTapDetectingView : UIView @property (nonatomic, weak) id <DXTapDetectingViewDelegate> tapDelegate; @end @protocol DXTapDetectingViewDelegate <NSObject> @optional - (void)view:(UIView *)view singleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view tripleTapDetected:(UITouch *)touch; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXTapDetectingView.m
Objective-C
// // UIViewTap.m // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import "DXTapDetectingView.h" @implementation DXTapDetectingView - (id)init { if ((self = [super init])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; NSUInteger tapCount = touch.tapCount; switch (tapCount) { case 1: [self handleSingleTap:touch]; break; case 2: [self handleDoubleTap:touch]; break; case 3: [self handleTripleTap:touch]; break; default: break; } [[self nextResponder] touchesEnded:touches withEvent:event]; } - (void)handleSingleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:singleTapDetected:)]) [_tapDelegate view:self singleTapDetected:touch]; } - (void)handleDoubleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:doubleTapDetected:)]) [_tapDelegate view:self doubleTapDetected:touch]; } - (void)handleTripleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:tripleTapDetected:)]) [_tapDelegate view:self tripleTapDetected:touch]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXZoomingScrollView.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @class DXZoomingScrollView, DXTapDetectingImageView; @protocol DXPhoto; @protocol DXZoomingScrollViewDelegate <NSObject> - (void)zoomingScrollViewSingleTapped:(DXZoomingScrollView *)zoomingScrollView; @end @interface DXZoomingScrollView : UIScrollView<UIScrollViewDelegate> @property (nonatomic, assign) NSUInteger index; @property (nonatomic, strong) id<DXPhoto> photo; @property (nonatomic, weak, readonly) id<DXZoomingScrollViewDelegate>zoomDelegate; @property (nonatomic, strong, readonly) DXTapDetectingImageView *imageView; @property (nonatomic, strong) UIImage *placeholder; - (id)initWithDelegate:(id<DXZoomingScrollViewDelegate>)delegate; - (void)prepareForReuse; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXZoomingScrollView.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXZoomingScrollView.h" #import "DXErrorIndicator.h" #import "DXTapDetectingImageView.h" #import "DXTapDetectingView.h" #import "DXPhoto.h" @interface DXZoomingScrollView ()<DXTapDetectingImageViewDelegate, DXTapDetectingViewDelegate> { DXTapDetectingView *_tapView; // for background taps DXTapDetectingImageView *_imageView; UIActivityIndicatorView *_loadingIndicator; CGSize _imageSize; } @property (nonatomic, strong) DXErrorIndicator *errorPlaceholder; @end @implementation DXZoomingScrollView - (id)initWithDelegate:(id<DXZoomingScrollViewDelegate>)delegate { if (self = [super init]) { _zoomDelegate = delegate; _index = NSUIntegerMax; UIViewAutoresizing autoresizingMaskWidthAndHeight = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); _tapView = [[DXTapDetectingView alloc] initWithFrame:self.bounds]; _tapView.tapDelegate = self; _tapView.autoresizingMask = autoresizingMaskWidthAndHeight; _tapView.backgroundColor = [UIColor clearColor]; _tapView.tapDelegate = self; [self addSubview:_tapView]; _imageView = [[DXTapDetectingImageView alloc] initWithFrame:CGRectZero]; _imageView.contentMode = UIViewContentModeScaleAspectFill; _imageView.clipsToBounds = YES; _imageView.tapDelegate = self; _imageView.backgroundColor = [UIColor clearColor]; [self addSubview:_imageView]; // Loading indicator _loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; _loadingIndicator.userInteractionEnabled = NO; _loadingIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin; [self addSubview:_loadingIndicator]; self.backgroundColor = [UIColor clearColor]; self.delegate = self; self.showsHorizontalScrollIndicator = NO; self.showsVerticalScrollIndicator = NO; self.decelerationRate = UIScrollViewDecelerationRateFast; self.autoresizingMask = autoresizingMaskWidthAndHeight; } return self; } - (void)hideLoadingIndicator { [_loadingIndicator stopAnimating]; _loadingIndicator.hidden = YES; } - (void)showLoadingIndicator { self.zoomScale = 0; self.minimumZoomScale = 0; self.maximumZoomScale = 0; [_loadingIndicator stopAnimating]; [_loadingIndicator startAnimating]; _loadingIndicator.hidden = NO; [_errorPlaceholder removeFromSuperview]; _errorPlaceholder = nil; } - (void)updateLoadingIndicatorWithProgress:(CGFloat)progress { [_loadingIndicator startAnimating]; } - (void)prepareForReuse { [_errorPlaceholder removeFromSuperview]; _errorPlaceholder = nil; if ([_photo respondsToSelector:@selector(cancelLoadImage)]) { [_photo cancelLoadImage]; } _photo = nil; _imageView.image = nil; _index = NSUIntegerMax; _imageSize = CGSizeZero; [self hideLoadingIndicator]; } - (void)setPhoto:(id<DXPhoto>)photo { _photo = photo; [self setupImageViewWithImage:[self placeholder]]; [self showLoadingIndicator]; __weak typeof(self) wself = self; [_photo loadImageWithProgressBlock:^(NSInteger receivedSize, NSInteger expectedSize) { [wself updateLoadingIndicatorWithProgress:(CGFloat)(receivedSize/expectedSize)]; } completionBlock:^(id<DXPhoto> aPhoto, UIImage *image) { if (!wself) return; [wself hideLoadingIndicator]; if (image && !CGSizeEqualToSize(image.size, CGSizeZero)) { [wself setupImageViewWithImage:image]; } else { [wself showErrorIndicator]; } }]; } - (void)setupImageViewWithImage:(UIImage *)image { self.maximumZoomScale = 1; self.minimumZoomScale = 1; self.zoomScale = 1; self.contentSize = CGSizeMake(0, 0); _imageSize = image.size; //set image _imageView.image = image; // Setup photo frame CGRect photoImageViewFrame; photoImageViewFrame.origin = CGPointZero; photoImageViewFrame.size = _imageSize; _imageView.frame = photoImageViewFrame; self.contentSize = photoImageViewFrame.size; // Set zoom to minimum zoom [self setMaxMinZoomScalesForCurrentBounds]; } - (void)showErrorIndicator { [self addSubview:self.errorPlaceholder]; _imageView.image = nil; } - (UIImage *)placeholder { UIImage *placeholder = nil; if ([_photo respondsToSelector:@selector(placeholder)]) { placeholder = [_photo placeholder]; } if (!placeholder) { placeholder = _placeholder; } return placeholder; } - (void)setMaxMinZoomScalesForCurrentBounds { // Reset self.maximumZoomScale = 1; self.minimumZoomScale = 1; self.zoomScale = 1; // Bail if no image if (_imageView.image == nil) return; // Reset position _imageView.frame = CGRectMake(0, 0, _imageView.frame.size.width, _imageView.frame.size.height); // Sizes CGSize boundsSize = self.bounds.size; CGSize imageSize = self->_imageSize; // Calculate Min // the scale needed to perfectly fit the image width-wise CGFloat xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image height-wise CGFloat yScale = boundsSize.height / imageSize.height; // use minimum of these to allow the image to become fully visible CGFloat minScale = MIN(xScale, yScale); // Calculate Max CGFloat maxScale = 3; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // Let them go a bit bigger on a bigger screen! maxScale = 4; } // Image is smaller than screen so no zooming! if (xScale >= 1 && yScale >= 1) { minScale = 1.0; } // Set min/max zoom self.maximumZoomScale = maxScale; self.minimumZoomScale = minScale; // Initial zoom self.zoomScale = [self initialZoomScaleWithMinScale]; // If we're zooming to fill then centralise if (self.zoomScale != minScale) { // Centralise self.contentOffset = CGPointMake((imageSize.width * self.zoomScale - boundsSize.width) / 2.0, (imageSize.height * self.zoomScale - boundsSize.height) / 2.0); // Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo self.scrollEnabled = NO; } // Layout [self setNeedsLayout]; } - (CGFloat)initialZoomScaleWithMinScale { CGFloat zoomScale = self.minimumZoomScale; if (_imageView) { // Zoom image to fill if the aspect ratios are fairly similar CGSize boundsSize = self.bounds.size; CGSize imageSize = self->_imageSize; CGFloat boundsAR = boundsSize.width / boundsSize.height; CGFloat imageAR = imageSize.width / imageSize.height; // the scale needed to perfectly fit the image width-wise CGFloat xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image height-wise CGFloat yScale = boundsSize.height / imageSize.height; // Zooms standard portrait images on a 3.5in screen but not on a 4in screen. if (ABS(boundsAR - imageAR) < 0.17) { zoomScale = MAX(xScale, yScale); // Ensure we don't zoom in or out too far, just in case zoomScale = MIN(MAX(self.minimumZoomScale, zoomScale), self.maximumZoomScale); } } return zoomScale; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return _imageView; } - (DXErrorIndicator *)errorPlaceholder { if (!_errorPlaceholder) { _errorPlaceholder = [[DXErrorIndicator alloc] initWithFrame:CGRectMake(0, 0, 44.0, 44.0)]; _errorPlaceholder.center = self.center; [_errorPlaceholder addTarget:self action:@selector(reloadDisplay) forControlEvents:UIControlEventTouchUpInside]; } return _errorPlaceholder; } - (void)reloadDisplay { self.photo = _photo; } - (void)layoutSubviews { // Position indicators (centre does not seem to work!) if (!_loadingIndicator.hidden) _loadingIndicator.frame = CGRectMake(floorf((self.bounds.size.width - _loadingIndicator.frame.size.width) / 2.), floorf((self.bounds.size.height - _loadingIndicator.frame.size.height) / 2), _loadingIndicator.frame.size.width, _loadingIndicator.frame.size.height); if (_errorPlaceholder) _errorPlaceholder.frame = CGRectMake(floorf((self.bounds.size.width - _errorPlaceholder.frame.size.width) / 2.), floorf((self.bounds.size.height - _errorPlaceholder.frame.size.height) / 2), _errorPlaceholder.frame.size.width, _errorPlaceholder.frame.size.height); // Super [super layoutSubviews]; // Center the image as it becomes smaller than the size of the screen CGSize boundsSize = self.bounds.size; CGRect frameToCenter = _imageView.frame; // Horizontally if (frameToCenter.size.width < boundsSize.width) { frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2.0); } else { frameToCenter.origin.x = 0; } // Vertically if (frameToCenter.size.height < boundsSize.height) { frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2.0); } else { frameToCenter.origin.y = 0; } // Center if (!CGRectEqualToRect(_imageView.frame, frameToCenter)) _imageView.frame = frameToCenter; } - (void)imageView:(UIImageView *)imageView doubleTapDetected:(UITouch *)touch { [self handleDoubleTap:[touch locationInView:imageView]]; } // Background View - (void)view:(UIView *)view singleTapDetected:(UITouch *)touch { // Translate touch location to image view location CGFloat touchX = [touch locationInView:view].x; CGFloat touchY = [touch locationInView:view].y; touchX *= 1/self.zoomScale; touchY *= 1/self.zoomScale; touchX += self.contentOffset.x; touchY += self.contentOffset.y; [self handleSingleTap:CGPointMake(touchX, touchY)]; } - (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch { // Translate touch location to image view location CGFloat touchX = [touch locationInView:view].x; CGFloat touchY = [touch locationInView:view].y; touchX *= 1/self.zoomScale; touchY *= 1/self.zoomScale; touchX += self.contentOffset.x; touchY += self.contentOffset.y; [self handleDoubleTap:CGPointMake(touchX, touchY)]; } - (void)handleSingleTap:(CGPoint)touchPoint { if ([_zoomDelegate respondsToSelector:@selector(zoomingScrollViewSingleTapped:)]) { [_zoomDelegate zoomingScrollViewSingleTapped:self]; } } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { [self setNeedsLayout]; [self layoutIfNeeded]; } - (void)handleDoubleTap:(CGPoint)touchPoint { // Zoom if (self.zoomScale != self.minimumZoomScale && self.zoomScale != [self initialZoomScaleWithMinScale]) { // Zoom out [self setZoomScale:self.minimumZoomScale animated:YES]; } else { // Zoom in to twice the size CGFloat newZoomScale = ((self.maximumZoomScale + self.minimumZoomScale) / 2); CGFloat xsize = self.bounds.size.width / newZoomScale; CGFloat ysize = self.bounds.size.height / newZoomScale; [self zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES]; } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/UIImage+DXAppleBlur.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (dx_AppleBlur) // apple wwdc session code for the blur - (UIImage *)dx_applyLightEffect; - (UIImage *)dx_applyExtraLightEffect; - (UIImage *)dx_applyDarkEffect; - (UIImage *)dx_applyGrayEffect; - (UIImage *)dx_applyTintEffectWithColor:(UIColor *)tintColor; - (UIImage *)dx_applyBlackEffect; - (UIImage *)dx_applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage; @end @interface UIImage (dx_Light) - (UIImage *)dx_cropImageWithRect:(CGRect)cropRect; - (BOOL)dx_isLight; - (UIColor *)dx_averageColor; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/UIImage+DXAppleBlur.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "UIImage+DXAppleBlur.h" #import <Accelerate/Accelerate.h> @implementation UIImage (dx_AppleBlur) - (UIImage *)dx_applyLightEffect { UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3]; return [self dx_applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyExtraLightEffect { UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyDarkEffect { UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyGrayEffect { UIColor *tintColor = [UIColor colorWithWhite:0.73 alpha:0.73]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyBlackEffect { UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73]; return [self dx_applyBlurWithRadius:10.0 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyTintEffectWithColor:(UIColor *)tintColor { const CGFloat EffectColorAlpha = 0.6; UIColor *effectColor = tintColor; size_t componentCount = CGColorGetNumberOfComponents(tintColor.CGColor); if (componentCount == 2) { CGFloat b; if ([tintColor getWhite:&b alpha:NULL]) { effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha]; } } else { CGFloat r, g, b; if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) { effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha]; } } return [self dx_applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil]; } - (UIImage *)dx_applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage { // check pre-conditions if (self.size.width < 1 || self.size.height < 1) { NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self); return nil; } if (!self.CGImage) { NSLog (@"*** error: image must be backed by a CGImage: %@", self); return nil; } if (maskImage && !maskImage.CGImage) { NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage); return nil; } CGRect imageRect = { CGPointZero, self.size }; UIImage *effectImage = self; BOOL hasBlur = blurRadius > __FLT_EPSILON__; BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__; if (hasBlur || hasSaturationChange) { UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef effectInContext = UIGraphicsGetCurrentContext(); CGContextScaleCTM(effectInContext, 1.0, -1.0); CGContextTranslateCTM(effectInContext, 0, -self.size.height); CGContextDrawImage(effectInContext, imageRect, self.CGImage); vImage_Buffer effectInBuffer; effectInBuffer.data = CGBitmapContextGetData(effectInContext); effectInBuffer.width = CGBitmapContextGetWidth(effectInContext); effectInBuffer.height = CGBitmapContextGetHeight(effectInContext); effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext); UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef effectOutContext = UIGraphicsGetCurrentContext(); vImage_Buffer effectOutBuffer; effectOutBuffer.data = CGBitmapContextGetData(effectOutContext); effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext); effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext); effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext); if (hasBlur) { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale]; uint32_t radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5); if (radius % 2 != 1) { radius += 1; // force radius to be odd so that the three box-blur methodology works. } vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); } BOOL effectImageBuffersAreSwapped = NO; if (hasSaturationChange) { CGFloat s = saturationDeltaFactor; CGFloat floatingPointSaturationMatrix[] = { 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1, }; const int32_t divisor = 256; NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]); int16_t saturationMatrix[matrixSize]; for (NSUInteger i = 0; i < matrixSize; ++i) { saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor); } if (hasBlur) { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags); effectImageBuffersAreSwapped = YES; } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags); } } if (!effectImageBuffersAreSwapped) effectImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (effectImageBuffersAreSwapped) effectImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } // set up output context UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef outputContext = UIGraphicsGetCurrentContext(); CGContextScaleCTM(outputContext, 1.0, -1.0); CGContextTranslateCTM(outputContext, 0, -self.size.height); // draw base image CGContextDrawImage(outputContext, imageRect, self.CGImage); // draw effect image if (hasBlur) { CGContextSaveGState(outputContext); if (maskImage) { CGContextClipToMask(outputContext, imageRect, maskImage.CGImage); } CGContextDrawImage(outputContext, imageRect, effectImage.CGImage); CGContextRestoreGState(outputContext); } // add in color tint if (tintColor) { CGContextSaveGState(outputContext); CGContextSetFillColorWithColor(outputContext, tintColor.CGColor); CGContextFillRect(outputContext, imageRect); CGContextRestoreGState(outputContext); } // output image is ready UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return outputImage; } @end @implementation UIImage (dx_Light) - (UIImage *)dx_cropImageWithRect:(CGRect)cropRect { if (CGSizeEqualToSize(self.size, CGSizeZero)) return nil; CGFloat scale = [UIScreen mainScreen].scale; cropRect = CGRectMake(cropRect.origin.x * scale, cropRect.origin.y * scale, cropRect.size.width * scale, cropRect.size.height * scale); UIGraphicsBeginImageContextWithOptions(cropRect.size, NO, 0); CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], cropRect); UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); [croppedImage drawInRect:CGRectMake(0, 0, cropRect.size.width, cropRect.size.height)]; UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); return resultImage; } - (BOOL)dx_isLight { BOOL imageIsLight = NO; CGImageRef imageRef = [self CGImage]; CGDataProviderRef dataProviderRef = CGImageGetDataProvider(imageRef); NSData *pixelData = (__bridge_transfer NSData *)CGDataProviderCopyData(dataProviderRef); if ([pixelData length] > 0) { const UInt8 *pixelBytes = [pixelData bytes]; // Whether or not the image format is opaque, the first byte is always the alpha component, followed by RGB. UInt8 pixelR = pixelBytes[1]; UInt8 pixelG = pixelBytes[2]; UInt8 pixelB = pixelBytes[3]; // Calculate the perceived luminance of the pixel; the human eye favors green, followed by red, then blue. double percievedLuminance = 1 - (((0.299 * pixelR) + (0.587 * pixelG) + (0.114 * pixelB)) / 255); imageIsLight = percievedLuminance < 0.5; } return imageIsLight; } - (UIColor *)dx_averageColor { CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); unsigned char rgba[4]; CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage); CGColorSpaceRelease(colorSpace); CGContextRelease(context); if(rgba[3] > 0) { CGFloat alpha = ((CGFloat)rgba[3])/255.0; CGFloat multiplier = alpha/255.0; return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier green:((CGFloat)rgba[1])*multiplier blue:((CGFloat)rgba[2])*multiplier alpha:alpha]; } else { return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0 green:((CGFloat)rgba[1])/255.0 blue:((CGFloat)rgba[2])/255.0 alpha:((CGFloat)rgba[3])/255.0]; } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/UIView+DXScreenShot.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (DXScreenShot) - (UIImage *)dx_screenShotImage; - (UIImage *)dx_screenShotImageAfterScreenUpdates:(BOOL)update; - (UIImage *)dx_screenShotImageWithBounds:(CGRect)selfBounds afterScreenUpdates:(BOOL)update; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/UIView+DXScreenShot.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "UIView+DXScreenShot.h" @implementation UIView (DXScreenShot) - (UIImage *)dx_screenShotImageWithBounds:(CGRect)selfBounds afterScreenUpdates:(BOOL)update { UIGraphicsBeginImageContextWithOptions(selfBounds.size, NO, 0); // The ios7 faster screenshot image method if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { [self drawViewHierarchyInRect:CGRectMake(-selfBounds.origin.x, -selfBounds.origin.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) afterScreenUpdates:update]; }else { [self.layer renderInContext:UIGraphicsGetCurrentContext()]; } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } - (UIImage *)dx_screenShotImage { return [self dx_screenShotImageWithBounds:self.bounds afterScreenUpdates:NO]; } - (UIImage *)dx_screenShotImageAfterScreenUpdates:(BOOL)update { return [self dx_screenShotImageWithBounds:self.bounds afterScreenUpdates:update]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXErrorIndicator.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface DXErrorIndicator : UIButton @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXErrorIndicator.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXErrorIndicator.h" #import "DXShapeImageLayer.h" @implementation DXErrorIndicator - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { DXCrossLayer *cross = [DXCrossLayer new]; cross.bounds = self.bounds; [self setImage:cross.normalImage forState:UIControlStateNormal]; } return self; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXPhoto.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @protocol DXPhoto <NSObject> typedef void (^DXPhotoProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); typedef void (^DXPhotoCompletionBlock)(id<DXPhoto>, UIImage *image); @required - (void)loadImageWithProgressBlock:(DXPhotoProgressBlock)progressBlock completionBlock:(DXPhotoCompletionBlock)completionBlock; @optional - (UIImage *)placeholder; - (void)cancelLoadImage; /** * Uses animation for expand and shrink, if not provide default is screenBounds. * Uses pixels size instead of point * * @return an expectLoadedImageSize; */ - (CGSize)expectLoadedImageSize; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXPhotoBrowser.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <Foundation/Foundation.h> #import "DXPhoto.h" @protocol DXPhotoBrowserDelegate; @class DXPullToDetailView; @interface DXPhotoBrowser : NSObject /** * Desigated intializer * * @param photosArray an array of id<DXPhoto> * */ - (instancetype)initWithPhotosArray:(NSArray *)photosArray; @property (nonatomic, strong, readonly) NSArray *photosArray; // if you imp the delegate method "simplePhotoBrowserDidTriggerPullToRightEnd:", then maybe you need to set the text @property (nonatomic, strong, readonly) DXPullToDetailView *pullToRightControl; // if current photos.count > 10, it will hidden @property (nonatomic, strong, readonly) UIPageControl *pageControl; @property (nonatomic, weak) id<DXPhotoBrowserDelegate> delegate; /** * The showing photo api * * @param index the index of within the photosArray * @param thumbnailView the animation from view, if set to nil, it will display without the expand animation */ - (void)showPhotoAtIndex:(NSUInteger)index withThumbnailImageView:(UIView *)thumbnailView; - (void)hide; @end @protocol DXPhotoBrowserDelegate <NSObject> @optional /** * * 如果要改变当前statusBarStyle的话, 这些delegate可以用到。 * 记得在info.plist里添加`UIViewControllerBasedStatusBarAppearance == NO` * */ - (void)simplePhotoBrowserWillShow:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidShow:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserWillHide:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidHide:(DXPhotoBrowser *)photoBrowser; - (void)simplePhotoBrowserDidTriggerPullToRightEnd:(DXPhotoBrowser *)photoBrowser; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXPhotoBrowser.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXPhotoBrowser.h" #import "UIView+DXScreenShot.h" #import "UIImage+DXAppleBlur.h" #import "DXPullToDetailView.h" #import "DXZoomingScrollView.h" #import "DXTapDetectingImageView.h" #import "DXTapDetectingView.h" static const CGFloat kPadding = 10.0; static inline NSTimeInterval durationToAnimate(CGFloat pointsToAnimate, CGFloat velocity) { NSTimeInterval animationDuration = pointsToAnimate / ABS(velocity); return animationDuration; } static inline CGSize screenRatioSize(CGSize fullScreenSize, CGSize originViewSize) { CGFloat x, X, y, Y, rx, ry; x = originViewSize.width; X = fullScreenSize.width; y = originViewSize.height; Y = fullScreenSize.height; // we use the bigger ratio if (x / X > y / Y) { rx = X; ry = X / x * y; } else { ry = Y; rx = Y / y * x; } return CGSizeMake(rx, ry); } @interface DXPhotoBrowser ()<UIScrollViewDelegate, DXZoomingScrollViewDelegate> @property (nonatomic, weak) UIView *sourceView; @property (nonatomic, weak) UIImage *scaleImage; @property (nonatomic, strong, readonly) UIView *fullcreenView; @property (nonatomic, strong, readonly) UIControl *backgroundView; // if current photos.count > 10, it will hidden @property (nonatomic, strong) UIPageControl *pageControl; /** * Default is yes, if under iOS7, then not */ @property (nonatomic, assign, getter=isBouncingAnimation) BOOL bouncingAnimation; /** * Default is 0.3 */ @property (nonatomic, assign) CGFloat flyInAnimationDuration; /** * Default is 0.3 */ @property (nonatomic, assign) CGFloat flyOutAnimationDuration; @end @implementation DXPhotoBrowser { UIView *_fullscreenView; UIControl *_backgroundView; UIScrollView *_pagingScrollView; NSMutableSet *_visiblePages, *_recycledPages; NSUInteger _currentPageIndex; NSUInteger _showStartIndex; NSUInteger _photoCount; DXPullToDetailView *_pullToRightControl; UIPanGestureRecognizer *_dismissPanGesture; NSArray *_photosArray; CGRect _sourceViewHereFrame; CGFloat _startShowingIndex; BOOL _isiOS7; struct { unsigned int delegateImpWillShowObj:1; unsigned int delegateImpDidShowObj:1; unsigned int delegateImpWillHideObj:1; unsigned int delegateImpDidHideObj:1; unsigned int delegateImpTriggerPullToRight:1; } _delegateFlags; } @synthesize fullcreenView = _fullscreenView, backgroundView = _backgroundView; #pragma -mark lifecycle - (void)dealloc { [_fullscreenView removeFromSuperview]; [_backgroundView removeFromSuperview]; _delegate = nil; } - (instancetype)init { NSAssert(NO, @"Please use initWithPhotosArray: instead"); return nil; } - (void)commonInit { UIViewAutoresizing autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); self.flyInAnimationDuration = 0.3; self.flyOutAnimationDuration = 0.3; self.bouncingAnimation = YES; _isiOS7 = [[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending; _fullscreenView = [[UIView alloc] init]; [_fullscreenView setAutoresizingMask:autoresizingMask]; _backgroundView = [[UIControl alloc] init]; [_backgroundView setAutoresizingMask:autoresizingMask]; [_backgroundView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.8]]; [_backgroundView addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside]; CGRect pagingScrollViewFrame = [self frameForPagingScrollView]; _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame]; _pagingScrollView.autoresizingMask = autoresizingMask; _pagingScrollView.pagingEnabled = YES; _pagingScrollView.delegate = self; _pagingScrollView.showsHorizontalScrollIndicator = NO; _pagingScrollView.showsVerticalScrollIndicator = NO; _pagingScrollView.backgroundColor = [UIColor clearColor]; _pagingScrollView.contentSize = [self contentSizeForPagingScrollView]; _pullToRightControl = [[DXPullToDetailView alloc] initWithFrame:_pagingScrollView.bounds]; _pullToRightControl.releasingText = @"请配置释放文案"; _pullToRightControl.pullingText = @"请配置滑动文案"; _pageControl = [[UIPageControl alloc] init]; _pageControl.userInteractionEnabled = NO; //recycle staff _visiblePages = [[NSMutableSet alloc] init]; _recycledPages = [[NSMutableSet alloc] init]; _photoCount = NSNotFound; _currentPageIndex = 0; _dismissPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; _dismissPanGesture.maximumNumberOfTouches = 1; _dismissPanGesture.minimumNumberOfTouches = 1; _delegateFlags.delegateImpWillShowObj = 0; _delegateFlags.delegateImpDidShowObj = 0; _delegateFlags.delegateImpWillHideObj = 0; _delegateFlags.delegateImpDidHideObj = 0; _delegateFlags.delegateImpTriggerPullToRight = 0; } - (instancetype)initWithPhotosArray:(NSArray *)photosArray { if (self = [super init]) { [self commonInit]; _photosArray = photosArray; } return self; } - (void)setDelegate:(id<DXPhotoBrowserDelegate>)delegate { if (_delegate != delegate) { _delegateFlags.delegateImpWillShowObj = [delegate respondsToSelector:@selector(simplePhotoBrowserWillShow:)]; _delegateFlags.delegateImpDidShowObj = [delegate respondsToSelector:@selector(simplePhotoBrowserDidShow:)]; _delegateFlags.delegateImpWillHideObj = [delegate respondsToSelector:@selector(simplePhotoBrowserWillHide:)]; _delegateFlags.delegateImpDidHideObj = [delegate respondsToSelector:@selector(simplePhotoBrowserDidHide:)]; _delegateFlags.delegateImpTriggerPullToRight = [delegate respondsToSelector:@selector(simplePhotoBrowserDidTriggerPullToRightEnd:)]; _delegate = delegate; } } #pragma -mark scrollView events - (CGRect)frameForPagingScrollView { CGRect frame = [_fullscreenView bounds]; frame.origin.x -= kPadding; frame.size.width += (2 * kPadding); return CGRectIntegral(frame); } - (CGSize)contentSizeForPagingScrollView { // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above. CGRect bounds = _pagingScrollView.bounds; return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height); } - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index { CGFloat pageWidth = _pagingScrollView.bounds.size.width; CGFloat newOffset = index * pageWidth; return CGPointMake(newOffset, 0); } - (CGRect)frameForPageAtIndex:(NSUInteger)index { // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape // because it has a rotation transform applied. CGRect bounds = _pagingScrollView.bounds; CGRect pageFrame = bounds; pageFrame.size.width -= (2 * kPadding); pageFrame.origin.x = (bounds.size.width * index) + kPadding; return CGRectIntegral(pageFrame); } - (NSUInteger)numberOfPhotos { return _photosArray.count; } - (void)resetPagingScrollView { // Reset _photoCount = NSNotFound; // Get data NSUInteger numberOfPhotos = [self numberOfPhotos]; // Update current page index if (numberOfPhotos > 0) { _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1)); } else { _currentPageIndex = 0; } // Update layout while (_pagingScrollView.subviews.count) { [[_pagingScrollView.subviews lastObject] removeFromSuperview]; } // Setup pages [_visiblePages removeAllObjects]; [_recycledPages removeAllObjects]; _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex]; [_pagingScrollView setFrame:[self frameForPagingScrollView]]; [_pagingScrollView setContentSize:[self contentSizeForPagingScrollView]]; [_pagingScrollView setAlpha:0.0]; _pagingScrollView.delegate = self; } - (void)tilePages { // Calculate which pages should be visible // Ignore padding as paging bounces encroach on that // and lead to false page loads CGRect visibleBounds = _pagingScrollView.bounds; NSInteger firstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds) + kPadding * 2) / CGRectGetWidth(visibleBounds)); NSInteger lastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds) - kPadding * 2 - 1) / CGRectGetWidth(visibleBounds)); if (firstIndex < 0) firstIndex = 0; if (firstIndex > [self numberOfPhotos] - 1) firstIndex = [self numberOfPhotos] - 1; if (lastIndex < 0) lastIndex = 0; if (lastIndex > [self numberOfPhotos] - 1) lastIndex = [self numberOfPhotos] - 1; // Recycle no longer needed pages NSInteger pageIndex; for (DXZoomingScrollView *page in _visiblePages) { pageIndex = page.index; if (pageIndex < firstIndex || pageIndex > lastIndex) { [_recycledPages addObject:page]; [page prepareForReuse]; [page removeFromSuperview]; } } [_visiblePages minusSet:_recycledPages]; while (_recycledPages.count > 3) // Only keep 3 recycled pages [_recycledPages removeObject:[_recycledPages anyObject]]; // Add missing pages for (NSUInteger index = firstIndex; index <= lastIndex; index++) { if (![self isDisplayingPageForIndex:index]) { // Add new page DXZoomingScrollView *page = [self dequeueRecycledPage]; if (!page) { page = [[DXZoomingScrollView alloc] initWithDelegate:self]; } [_visiblePages addObject:page]; [self configurePage:page forIndex:index]; [_pagingScrollView addSubview:page]; } } } - (BOOL)isDisplayingPageForIndex:(NSUInteger)index { for (DXZoomingScrollView *page in _visiblePages) if (page.index == index) return YES; return NO; } - (DXZoomingScrollView *)dequeueRecycledPage { DXZoomingScrollView *page = [_recycledPages anyObject]; if (page) { [_recycledPages removeObject:page]; } return page; } - (void)configurePage:(DXZoomingScrollView *)page forIndex:(NSUInteger)index { page.frame = [self frameForPageAtIndex:index]; page.index = index; page.photo = [self photoAtIndex:index]; } - (id<DXPhoto>)photoAtIndex:(NSUInteger)index { id<DXPhoto> cellObj = nil; if (index < _photosArray.count) { cellObj = _photosArray[index]; } if (![cellObj conformsToProtocol:@protocol(DXPhoto)]) { NSLog(@"HRSimplePhotoBrowser photos array object at index %lu does conforms to protocol <HRPhoto>", (unsigned long)index); return nil; } return cellObj; } - (DXZoomingScrollView *)pageAtIndex:(NSUInteger)index { for (DXZoomingScrollView *page in _visiblePages) { if (page.index == _currentPageIndex) { return page; } } return nil; } - (BOOL)isSatisfiedJumpWithScrollView:(UIScrollView *)scrollView { BOOL satisfy = (scrollView.contentOffset.x + CGRectGetWidth(scrollView.bounds) - scrollView.contentSize.width > 60.0); return satisfy; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self tilePages]; CGRect visibleBounds = _pagingScrollView.bounds; NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))); if (index < 0) index = 0; if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1; _currentPageIndex = index; _pageControl.currentPage = _currentPageIndex; // moved 60.0 if ([self isSatisfiedJumpWithScrollView:scrollView]) { if (scrollView.isDragging == YES) { [_pullToRightControl setPulling:YES animated:YES]; }else { // iOS6 当pageEnabled == YES的时候无法判断速度, 这里降级处理 if (!_isiOS7) { if (_delegateFlags.delegateImpTriggerPullToRight) { [self hideAnimated:NO]; scrollView.delegate = nil; [self.delegate simplePhotoBrowserDidTriggerPullToRightEnd:self]; } } } }else { [_pullToRightControl setPulling:NO animated:YES]; } } - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { if ([self isSatisfiedJumpWithScrollView:scrollView]) { if (velocity.x < 1.0) { if (_delegateFlags.delegateImpTriggerPullToRight) { [self hideAnimated:NO]; scrollView.delegate = nil; [self.delegate simplePhotoBrowserDidTriggerPullToRightEnd:self]; } } } } - (void)tilePagesAtIndex:(NSUInteger)index { CGRect bounds = _pagingScrollView.bounds; bounds.origin.x = [self contentOffsetForPageAtIndex:index].x; _pagingScrollView.bounds = bounds; _currentPageIndex = index; _pageControl.numberOfPages = [self numberOfPhotos]; _pageControl.currentPage = _currentPageIndex; _pageControl.hidden = _pageControl.numberOfPages <= 1; [_pageControl sizeToFit]; CGPoint pageCenter = _pagingScrollView.center; pageCenter.y = CGRectGetHeight(_pagingScrollView.bounds) - CGRectGetHeight(_pageControl.bounds); _pageControl.center = pageCenter; [self tilePages]; } - (void)handlePan:(id)sender { // Initial Setup DXZoomingScrollView *scrollView = [self pageAtIndex:_currentPageIndex]; static CGFloat firstX, firstY; CGFloat viewHeight = scrollView.frame.size.height; CGFloat viewHalfHeight = viewHeight / 2; CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:_fullscreenView ]; CGPoint velocity = [(UIPanGestureRecognizer*)sender velocityInView:_fullscreenView]; // Gesture Began if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { firstX = [scrollView center].x; firstY = [scrollView center].y; } translatedPoint = CGPointMake(firstX, firstY+translatedPoint.y); [scrollView setCenter:translatedPoint]; CGFloat newY = scrollView.center.y - viewHalfHeight; CGFloat newAlpha = 1 - ABS(newY) / viewHeight; _backgroundView.opaque = YES; _backgroundView.alpha = newAlpha; // Gesture Ended if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) { CGFloat autoDismissOffset = 50.0; // if moved > autoDismissOffset if (scrollView.center.y > viewHalfHeight + autoDismissOffset || scrollView.center.y < viewHalfHeight - autoDismissOffset) { if (_sourceView && _currentPageIndex == _startShowingIndex) { [self hide]; return; } CGFloat finalX = firstX, finalY; CGFloat windowsHeigt = _fullscreenView.bounds.size.height; if(scrollView.center.y > viewHalfHeight + 30) // swipe down finalY = windowsHeigt * 2; else // swipe up finalY = -viewHalfHeight; CGFloat animationDuration = durationToAnimate(windowsHeigt * 0.5, ABS(velocity.y)); if (animationDuration < 0.1) animationDuration = 0.1; if (animationDuration > 0.35) animationDuration = 0.35; [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^ { [scrollView setCenter:CGPointMake(finalX, finalY)]; } completion:NULL]; [self performSelector:@selector(hide) withObject:self afterDelay:animationDuration]; } else { // continue show part CGFloat velocityY = (.35 * velocity.y); CGFloat finalX = firstX; CGFloat finalY = viewHalfHeight; CGFloat animationDuration = (ABS(velocityY) * 0.0002)+ 0.2; [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^ { [scrollView setCenter:CGPointMake(finalX, finalY)]; _backgroundView.alpha = 1.0; } completion:NULL]; } } } #pragma -mark show & hide - (void)showPhotoAtIndex:(NSUInteger)index withThumbnailImageView:(UIView *)thumbnailView { if (index > _photosArray.count) { NSLog(@"Expected showing photo index %lu is out of range with total photos count %lu and current index", (unsigned long)index, (unsigned long)_photosArray.count); index = 0; } if (!_photosArray || _photosArray.count == 0) return; _startShowingIndex = index; // setup the root view UIView *rootViewControllerView = [[UIApplication sharedApplication] keyWindow].rootViewController.view; [_fullscreenView setFrame:[rootViewControllerView bounds]]; [rootViewControllerView addSubview:_fullscreenView]; [_fullscreenView addGestureRecognizer:_dismissPanGesture]; // Stash away original thumbnail image view information _sourceView = thumbnailView; _sourceViewHereFrame = [_sourceView.superview convertRect:_sourceView.frame toView:_fullscreenView]; _sourceView.hidden = YES; // Configure the background view, iOS6的截图效率太低,这里使用半透明黑色背景替代 UIColor *backgroundColor; if (_isiOS7) { UIImage *screenShotImage = [rootViewControllerView dx_screenShotImageAfterScreenUpdates:NO]; screenShotImage = [screenShotImage dx_applyBlackEffect]; backgroundColor = [UIColor colorWithPatternImage:screenShotImage]; }else { backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7]; } _backgroundView.backgroundColor = backgroundColor; [_backgroundView setFrame:[_fullscreenView bounds]]; [_backgroundView setAlpha:0]; [_fullscreenView addSubview:_backgroundView]; // reset the page scrollView [self resetPagingScrollView]; [self tilePagesAtIndex:index]; [_fullscreenView addSubview:_pagingScrollView]; // pullToDetailView if (_delegateFlags.delegateImpTriggerPullToRight) { _pullToRightControl.frame = CGRectMake((_pagingScrollView.contentSize.width), 0, 44.0, CGRectGetHeight(_pagingScrollView.bounds)); [_pagingScrollView addSubview:_pullToRightControl]; } else { [_pullToRightControl removeFromSuperview]; } // pagecontrol _pageControl.hidden = _photosArray.count > 10; // Get the target image for animation id<DXPhoto> currentPhoto = [self photoAtIndex:_currentPageIndex]; if ([currentPhoto respondsToSelector:@selector(placeholder)]) { _scaleImage = [currentPhoto placeholder]; } if (!_scaleImage) { _scaleImage = [_sourceView dx_screenShotImageAfterScreenUpdates:NO]; } [self performAnimateFlyIn]; } - (void)performAnimateFlyIn { UIImage *imageFromView = _scaleImage; // The destination imageSize, if the image has loaded we use it CGRect screenBound = [[[self pageAtIndex:_currentPageIndex] imageView] frame]; // otherwise we use the protocol size if (CGSizeEqualToSize(screenBound.size, CGSizeZero)) { id<DXPhoto> currentPhoto = [self photoAtIndex:_currentPageIndex]; CGSize imageSize = CGSizeZero; if ([currentPhoto respondsToSelector:@selector(expectLoadedImageSize)]) { imageSize = [currentPhoto expectLoadedImageSize]; } // last solution we use the screen size if (CGSizeEqualToSize(imageSize, CGSizeZero) && _sourceView) { imageSize = screenRatioSize(_fullscreenView.bounds.size, _sourceView.bounds.size); } screenBound = CGRectMake(0, 0, imageSize.width, imageSize.height); } UIImageView *resizableImageView; CGRect finalImageViewFrame; if (!CGSizeEqualToSize(screenBound.size, CGSizeZero) && _sourceView) { CGFloat screenWidth = screenBound.size.width; CGFloat screenHeight = screenBound.size.height; resizableImageView = [[UIImageView alloc] initWithImage:imageFromView]; resizableImageView.frame = _sourceViewHereFrame; resizableImageView.clipsToBounds = YES; resizableImageView.contentMode = UIViewContentModeScaleAspectFill; [_fullscreenView addSubview:resizableImageView]; finalImageViewFrame = CGRectMake((CGRectGetWidth(_fullscreenView.bounds) - screenWidth) * 0.5, (CGRectGetHeight(_fullscreenView.bounds) - screenHeight) * 0.5, screenWidth, screenHeight); } if (_delegateFlags.delegateImpWillShowObj) { [_delegate simplePhotoBrowserWillShow:self]; } dispatch_block_t animation = ^{ [_backgroundView setAlpha:1.0]; if (resizableImageView) { resizableImageView.layer.frame = finalImageViewFrame; } else { [_pagingScrollView setAlpha:1.0]; } }; dispatch_block_t completion = ^{ [resizableImageView removeFromSuperview]; [_pagingScrollView setAlpha:1.0]; if (_delegateFlags.delegateImpDidShowObj) { [_delegate simplePhotoBrowserDidShow:self]; } }; if (self.isBouncingAnimation && _isiOS7) { [UIView animateWithDuration:self.flyInAnimationDuration + 0.1 delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:6.0 options:UIViewAnimationOptionCurveEaseIn animations:animation completion:^(BOOL finished) { completion(); }]; }else { [UIView animateWithDuration:self.flyInAnimationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:animation completion:^(BOOL finished) { completion(); }]; } } - (void)hide { [self hideAnimated:YES]; } - (BOOL)shouldAnimateSourceViewFrame { return _sourceView && _currentPageIndex == _startShowingIndex; } - (void)hideAnimated:(BOOL)animated { CGFloat duration = 0.0; if (animated) duration = self.flyOutAnimationDuration; if ([self shouldAnimateSourceViewFrame] && duration > 0) { DXZoomingScrollView *scrollView = [self pageAtIndex:_currentPageIndex]; [self performHideAnimatioWithScrollView:scrollView withDuration:duration]; }else { _sourceView.hidden = NO; } [_pagingScrollView setAlpha:0.0]; [UIView animateWithDuration:duration animations:^{ [_backgroundView setAlpha:0]; } completion:^(BOOL finished) { _sourceView.hidden = NO; _scaleImage = nil; [_pageControl removeFromSuperview]; [_pagingScrollView removeFromSuperview]; [_backgroundView removeFromSuperview]; [_fullscreenView removeFromSuperview]; _pagingScrollView.alpha = 1.0; _pagingScrollView.transform = CGAffineTransformIdentity; [_fullscreenView removeGestureRecognizer:_dismissPanGesture]; // Inform the delegate that we just hide a fullscreen photo if (_delegateFlags.delegateImpDidHideObj) { [_delegate simplePhotoBrowserDidHide:self]; } }]; } - (void)performHideAnimatioWithScrollView:(DXZoomingScrollView *)scrollView withDuration:(CGFloat)duration { UIImage *imageFromView = nil; if ([scrollView.photo respondsToSelector:@selector(placeholder)]) { imageFromView = [scrollView.photo placeholder]; } CGRect screenBound = [[[self pageAtIndex:_currentPageIndex] imageView] frame]; UIImageView *resizableImageView; if (!CGSizeEqualToSize(screenBound.size, CGSizeZero)) { screenBound = [scrollView convertRect:screenBound toView:_fullscreenView]; resizableImageView = [[UIImageView alloc] initWithImage:imageFromView]; resizableImageView.frame = screenBound; resizableImageView.contentMode = UIViewContentModeScaleAspectFill; resizableImageView.backgroundColor = [UIColor clearColor]; resizableImageView.clipsToBounds = YES; [_fullscreenView addSubview:resizableImageView]; } dispatch_block_t animation = ^{ resizableImageView.layer.frame = _sourceViewHereFrame; }; dispatch_block_t completion = ^{ [resizableImageView removeFromSuperview]; }; if (self.isBouncingAnimation && _isiOS7) { [UIView animateWithDuration:duration + 0.1 delay:0.0 usingSpringWithDamping:0.9 initialSpringVelocity:4.0 options:UIViewAnimationOptionCurveEaseOut animations:animation completion:^(BOOL finished) { completion(); }]; }else { [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:animation completion:^(BOOL finished) { completion(); }]; } } - (void)zoomingScrollViewSingleTapped:(DXZoomingScrollView *)zoomingScrollView { [self hide]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXPullToDetailView.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface DXPullToDetailView : UIView @property (nonatomic, assign) BOOL pulling; @property (nonatomic, strong) NSString *pullingText; @property (nonatomic, strong) NSString *releasingText; @property (nonatomic, strong, readonly) UILabel *textLabel; - (void)setPulling:(BOOL)pulling animated:(BOOL)animated; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXPullToDetailView.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXPullToDetailView.h" #import "DXShapeImageLayer.h" @implementation DXPullToDetailView { UIImageView *_arrow; UILabel *_textLabel; } - (instancetype)initWithFrame:(CGRect)frame { frame.size.width = 200.0; self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; _arrow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20.0, 20.0)]; _arrow.center = CGPointMake(15.0, CGRectGetMidY(self.bounds)); UIImage *previewImage = [UIImage imageNamed:@"preview_indicator"]; if (!previewImage) { DXArrowLayer *arrowLayer = [DXArrowLayer new]; arrowLayer.bounds = _arrow.bounds; previewImage = [arrowLayer normalImage]; } _arrow.image = previewImage; [self addSubview:_arrow]; _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_arrow.frame) + 10.0, 0.0, 15.0, CGRectGetHeight(self.bounds))]; _textLabel.numberOfLines = 0.0; _textLabel.lineBreakMode = NSLineBreakByWordWrapping; _textLabel.textAlignment = NSTextAlignmentCenter; _textLabel.textColor = [UIColor whiteColor]; _textLabel.backgroundColor = [UIColor clearColor]; _textLabel.font = [UIFont systemFontOfSize:CGRectGetWidth(_textLabel.frame) - 1.0]; [self addSubview:_textLabel]; } return self; } - (void)setPulling:(BOOL)pulling animated:(BOOL)animated { CGFloat duration = animated ? 0.2 : 0.0; if (_pulling != pulling) { if (pulling) { [UIView animateWithDuration:duration animations:^{ _arrow.transform = CGAffineTransformMakeRotation((M_PI)); }]; _textLabel.text = _releasingText; } else { [UIView animateWithDuration:duration animations:^{ _arrow.transform = CGAffineTransformIdentity; }]; _textLabel.text = _pullingText; } _pulling = pulling; } } - (void)setPulling:(BOOL)pulling { [self setPulling:pulling animated:NO]; } - (void)willMoveToWindow:(UIWindow *)newWindow { [super willMoveToWindow:newWindow]; if (newWindow) { _arrow.transform = CGAffineTransformIdentity; _textLabel.text = _pullingText; } } - (void)layoutSubviews { [super layoutSubviews]; _arrow.center = CGPointMake(15.0, CGRectGetMidY(self.bounds)); _textLabel.frame = CGRectMake(CGRectGetMaxX(_arrow.frame) + 10.0, 0.0, 15.0, CGRectGetHeight(self.bounds)); } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXShapeImageLayer.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <QuartzCore/QuartzCore.h> @interface DXShapeImageLayer : CALayer @property (nonatomic, strong) UIColor *normalColor; @property (nonatomic, strong) UIColor *highlightedColor; /** * This shape which maded by this cells. * When subclass, remember to add you cells into this array */ @property (nonatomic, strong) NSMutableArray *cellLayers; - (UIImage *)normalImage; - (UIImage *)highlightedImage; @end @interface DXCrossLayer : DXShapeImageLayer /** * Default is 1.0 */ @property (nonatomic, assign) CGFloat crossLineWidth; /** * Use 45.0, 90.0 instead of PI */ @property (nonatomic, assign) CGFloat crossLineAngle; /** * Default is 1.0 */ @property (nonatomic, assign) CGFloat crossLineCornerRadius; @end @interface DXArrowLayer : DXShapeImageLayer /** * default is 1.0 */ @property (nonatomic, assign) CGFloat lineWidth; /** * default is 1.0 */ @property (nonatomic, assign) CGFloat circleLineWidth; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXShapeImageLayer.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #define dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(layer, nowAnchorPoint) \ CGPoint dx_lastAnchor = layer.anchorPoint;\ layer.anchorPoint = nowAnchorPoint;\ layer.position \ = CGPointMake(layer.position.x+(nowAnchorPoint.x-dx_lastAnchor.x)*layer.bounds.size.width, \ layer.position.y+(nowAnchorPoint.y-dx_lastAnchor.y)*layer.bounds.size.height);\ static inline CGFloat radians(CGFloat degrees) { return ( degrees * M_PI ) / 180.0; } #import "DXShapeImageLayer.h" @implementation DXShapeImageLayer - (instancetype)init { self = [super init]; if (self) { _normalColor = [UIColor whiteColor]; _highlightedColor = [UIColor darkGrayColor]; _cellLayers = [NSMutableArray array]; } return self; } - (UIImage *)normalImage { for (CALayer *layer in self.cellLayers) { layer.backgroundColor = self.normalColor.CGColor; } return [self toImage]; } - (UIImage *)highlightedImage { for (CALayer *layer in self.cellLayers) { layer.backgroundColor = self.highlightedColor.CGColor; } return [self toImage]; } - (UIImage *)toImage { CGSize size = self.bounds.size; if (CGSizeEqualToSize(size, CGSizeZero)) return nil; CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height); UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextClearRect(context, rect); [self renderInContext:context]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end @implementation DXCrossLayer { CALayer *_left; CALayer *_right; } - (instancetype)init { self = [super init]; if (self) { self.crossLineAngle = radians(45.0); self.crossLineWidth = 1.0; self.crossLineCornerRadius = 1.0; _left = [CALayer layer]; _right = [CALayer layer]; [self addSublayer:_left]; [self addSublayer:_right]; [self.cellLayers addObject:_left]; [self.cellLayers addObject:_right]; } return self; } - (void)setBounds:(CGRect)bounds { if (!CGRectEqualToRect(bounds, self.bounds)) { CGRect crossFrame = CGRectInset(bounds, (CGRectGetWidth(bounds) - self.crossLineWidth) * 0.5, 0.0); _left.frame = crossFrame; _right.frame = crossFrame; _left.transform = CATransform3DMakeRotation(-self.crossLineAngle, 0.0, 0.0, 1.0); _right.transform = CATransform3DMakeRotation(self.crossLineAngle, 0.0, 0.0, 1.0); [self setNeedsDisplay]; } [super setBounds:bounds]; } @end @implementation DXArrowLayer { CAShapeLayer *_circle; CALayer *_middleLine; CALayer *_upLine; CALayer *_downLine; } - (instancetype)init { self = [super init]; if (self) { _lineWidth = 1.0; _circleLineWidth = 1.0; self.masksToBounds = NO; _circle = [CAShapeLayer new]; _middleLine = [CALayer layer]; _upLine = [CALayer layer]; _downLine = [CALayer layer]; [self addSublayer:_circle]; [self addSublayer:_middleLine]; [self addSublayer:_upLine]; [self addSublayer:_downLine]; [self.cellLayers addObject:_circle]; [self.cellLayers addObject:_middleLine]; [self.cellLayers addObject:_upLine]; [self.cellLayers addObject:_downLine]; } return self; } - (void)setBounds:(CGRect)bounds { if (!CGRectEqualToRect(bounds, self.bounds)) { _circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(bounds, 1.0, 1.0) cornerRadius:CGRectGetMidX(bounds)].CGPath; _circle.lineWidth = _circleLineWidth; _circle.fillColor = [UIColor clearColor].CGColor; _circle.strokeColor = self.normalColor.CGColor; CGFloat middleLineWidth = bounds.size.width * 0.5; _middleLine.frame = CGRectMake((CGRectGetWidth(bounds) - middleLineWidth) * 0.5 , (CGRectGetHeight(bounds) - _lineWidth) * 0.5, middleLineWidth, _lineWidth); [self addSublayer:_middleLine]; [self setupUpLine]; [self setupDownLine]; [self setNeedsDisplay]; } [super setBounds:bounds]; } - (void)setupUpLine { _upLine.frame = CGRectMake(CGRectGetMinX(_middleLine.frame), CGRectGetMinY(_middleLine.frame), CGRectGetWidth(_middleLine.frame) * 0.5, _lineWidth); _upLine.transform = CATransform3DMakeRotation(-radians(40.0), 0.0, 0.0, 1.0); dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(_upLine, CGPointMake(0.0, 0.5)); [self addSublayer:_upLine]; } - (void)setupDownLine { _downLine.frame = CGRectMake(CGRectGetMinX(_middleLine.frame), CGRectGetMinY(_middleLine.frame), CGRectGetWidth(_middleLine.frame) * 0.5, _lineWidth); _downLine.transform = CATransform3DMakeRotation(radians(40.0), 0.0, 0.0, 1.0); dx_ChangeLayerAnchorPointAndAjustPositionToStayFrame(_downLine, CGPointMake(0.0, 0.5)); [self addSublayer:_downLine]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXTapDetectingImageView.h
C/C++ Header
// // UIImageViewTap.h // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import <Foundation/Foundation.h> @protocol DXTapDetectingImageViewDelegate; @interface DXTapDetectingImageView : UIImageView {} @property (nonatomic, weak) id <DXTapDetectingImageViewDelegate> tapDelegate; @end @protocol DXTapDetectingImageViewDelegate <NSObject> @optional - (void)imageView:(UIImageView *)imageView singleTapDetected:(UITouch *)touch; - (void)imageView:(UIImageView *)imageView doubleTapDetected:(UITouch *)touch; - (void)imageView:(UIImageView *)imageView tripleTapDetected:(UITouch *)touch; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXTapDetectingImageView.m
Objective-C
// // UIImageViewTap.m // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import "DXTapDetectingImageView.h" @implementation DXTapDetectingImageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithImage:(UIImage *)image { if ((self = [super initWithImage:image])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage { if ((self = [super initWithImage:image highlightedImage:highlightedImage])) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; NSUInteger tapCount = touch.tapCount; switch (tapCount) { case 1: [self handleSingleTap:touch]; break; case 2: [self handleDoubleTap:touch]; break; case 3: [self handleTripleTap:touch]; break; default: break; } [[self nextResponder] touchesEnded:touches withEvent:event]; } - (void)handleSingleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:singleTapDetected:)]) [_tapDelegate imageView:self singleTapDetected:touch]; } - (void)handleDoubleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:doubleTapDetected:)]) [_tapDelegate imageView:self doubleTapDetected:touch]; } - (void)handleTripleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(imageView:tripleTapDetected:)]) [_tapDelegate imageView:self tripleTapDetected:touch]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXTapDetectingView.h
C/C++ Header
// // UIViewTap.h // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import <Foundation/Foundation.h> @protocol DXTapDetectingViewDelegate; @interface DXTapDetectingView : UIView @property (nonatomic, weak) id <DXTapDetectingViewDelegate> tapDelegate; @end @protocol DXTapDetectingViewDelegate <NSObject> @optional - (void)view:(UIView *)view singleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view tripleTapDetected:(UITouch *)touch; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXTapDetectingView.m
Objective-C
// // UIViewTap.m // Momento // // Created by Michael Waterfall on 04/11/2009. // Copyright 2009 d3i. All rights reserved. // #import "DXTapDetectingView.h" @implementation DXTapDetectingView - (id)init { if ((self = [super init])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; NSUInteger tapCount = touch.tapCount; switch (tapCount) { case 1: [self handleSingleTap:touch]; break; case 2: [self handleDoubleTap:touch]; break; case 3: [self handleTripleTap:touch]; break; default: break; } [[self nextResponder] touchesEnded:touches withEvent:event]; } - (void)handleSingleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:singleTapDetected:)]) [_tapDelegate view:self singleTapDetected:touch]; } - (void)handleDoubleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:doubleTapDetected:)]) [_tapDelegate view:self doubleTapDetected:touch]; } - (void)handleTripleTap:(UITouch *)touch { if ([_tapDelegate respondsToSelector:@selector(view:tripleTapDetected:)]) [_tapDelegate view:self tripleTapDetected:touch]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXZoomingScrollView.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @class DXZoomingScrollView, DXTapDetectingImageView; @protocol DXPhoto; @protocol DXZoomingScrollViewDelegate <NSObject> - (void)zoomingScrollViewSingleTapped:(DXZoomingScrollView *)zoomingScrollView; @end @interface DXZoomingScrollView : UIScrollView<UIScrollViewDelegate> @property (nonatomic, assign) NSUInteger index; @property (nonatomic, strong) id<DXPhoto> photo; @property (nonatomic, weak, readonly) id<DXZoomingScrollViewDelegate>zoomDelegate; @property (nonatomic, strong, readonly) DXTapDetectingImageView *imageView; - (id)initWithDelegate:(id<DXZoomingScrollViewDelegate>)delegate; - (void)prepareForReuse; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/DXZoomingScrollView.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "DXZoomingScrollView.h" #import "DXErrorIndicator.h" #import "DXTapDetectingImageView.h" #import "DXTapDetectingView.h" #import "DXPhoto.h" @interface DXZoomingScrollView ()<DXTapDetectingImageViewDelegate, DXTapDetectingViewDelegate> { DXTapDetectingView *_tapView; // for background taps DXTapDetectingImageView *_imageView; UIActivityIndicatorView *_loadingIndicator; CGSize _imageSize; } @property (nonatomic, strong) DXErrorIndicator *errorPlaceholder; @end @implementation DXZoomingScrollView - (id)initWithDelegate:(id<DXZoomingScrollViewDelegate>)delegate { if (self = [super init]) { _zoomDelegate = delegate; _index = NSUIntegerMax; UIViewAutoresizing autoresizingMaskWidthAndHeight = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); _tapView = [[DXTapDetectingView alloc] initWithFrame:self.bounds]; _tapView.tapDelegate = self; _tapView.autoresizingMask = autoresizingMaskWidthAndHeight; _tapView.backgroundColor = [UIColor clearColor]; _tapView.tapDelegate = self; [self addSubview:_tapView]; _imageView = [[DXTapDetectingImageView alloc] initWithFrame:CGRectZero]; _imageView.contentMode = UIViewContentModeScaleAspectFill; _imageView.clipsToBounds = YES; _imageView.tapDelegate = self; _imageView.backgroundColor = [UIColor clearColor]; [self addSubview:_imageView]; // Loading indicator _loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; _loadingIndicator.userInteractionEnabled = NO; _loadingIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin; [self addSubview:_loadingIndicator]; self.backgroundColor = [UIColor clearColor]; self.delegate = self; self.showsHorizontalScrollIndicator = NO; self.showsVerticalScrollIndicator = NO; self.decelerationRate = UIScrollViewDecelerationRateFast; self.autoresizingMask = autoresizingMaskWidthAndHeight; } return self; } - (void)hideLoadingIndicator { [_loadingIndicator stopAnimating]; _loadingIndicator.hidden = YES; } - (void)showLoadingIndicator { self.zoomScale = 0; self.minimumZoomScale = 0; self.maximumZoomScale = 0; [_loadingIndicator stopAnimating]; [_loadingIndicator startAnimating]; _loadingIndicator.hidden = NO; [_errorPlaceholder removeFromSuperview]; _errorPlaceholder = nil; } - (void)updateLoadingIndicatorWithProgress:(CGFloat)progress { [_loadingIndicator startAnimating]; } - (void)prepareForReuse { [_errorPlaceholder removeFromSuperview]; _errorPlaceholder = nil; if ([_photo respondsToSelector:@selector(cancelLoadImage)]) { [_photo cancelLoadImage]; } _photo = nil; _imageView.image = nil; _index = NSUIntegerMax; _imageSize = CGSizeZero; [self hideLoadingIndicator]; } - (void)setPhoto:(id<DXPhoto>)photo { _photo = photo; [self showLoadingIndicator]; __weak typeof(self) wself = self; [_photo loadImageWithProgressBlock:^(NSInteger receivedSize, NSInteger expectedSize) { [wself updateLoadingIndicatorWithProgress:(CGFloat)(receivedSize/expectedSize)]; } completionBlock:^(id<DXPhoto> aPhoto, UIImage *image) { if (!wself) return; [wself hideLoadingIndicator]; if (image && !CGSizeEqualToSize(image.size, CGSizeZero)) { [wself setupImageViewWithImage:image]; } else { [wself showErrorIndicator]; } }]; } - (void)setupImageViewWithImage:(UIImage *)image { self.maximumZoomScale = 1; self.minimumZoomScale = 1; self.zoomScale = 1; self.contentSize = CGSizeMake(0, 0); _imageSize = image.size; //set image _imageView.image = image; // Setup photo frame CGRect photoImageViewFrame; photoImageViewFrame.origin = CGPointZero; photoImageViewFrame.size = _imageSize; _imageView.frame = photoImageViewFrame; self.contentSize = photoImageViewFrame.size; // Set zoom to minimum zoom [self setMaxMinZoomScalesForCurrentBounds]; } - (void)showErrorIndicator { [self addSubview:self.errorPlaceholder]; _imageView.image = [self placeholder]; } - (UIImage *)placeholder { if ([_photo respondsToSelector:@selector(placeholder)]) { return [_photo placeholder]; } return nil; } - (void)setMaxMinZoomScalesForCurrentBounds { // Reset self.maximumZoomScale = 1; self.minimumZoomScale = 1; self.zoomScale = 1; // Bail if no image if (_imageView.image == nil) return; // Reset position _imageView.frame = CGRectMake(0, 0, _imageView.frame.size.width, _imageView.frame.size.height); // Sizes CGSize boundsSize = self.bounds.size; CGSize imageSize = self->_imageSize; // Calculate Min // the scale needed to perfectly fit the image width-wise CGFloat xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image height-wise CGFloat yScale = boundsSize.height / imageSize.height; // use minimum of these to allow the image to become fully visible CGFloat minScale = MIN(xScale, yScale); // Calculate Max CGFloat maxScale = 3; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // Let them go a bit bigger on a bigger screen! maxScale = 4; } // Image is smaller than screen so no zooming! if (xScale >= 1 && yScale >= 1) { minScale = 1.0; } // Set min/max zoom self.maximumZoomScale = maxScale; self.minimumZoomScale = minScale; // Initial zoom self.zoomScale = [self initialZoomScaleWithMinScale]; // If we're zooming to fill then centralise if (self.zoomScale != minScale) { // Centralise self.contentOffset = CGPointMake((imageSize.width * self.zoomScale - boundsSize.width) / 2.0, (imageSize.height * self.zoomScale - boundsSize.height) / 2.0); // Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo self.scrollEnabled = NO; } // Layout [self setNeedsLayout]; } - (CGFloat)initialZoomScaleWithMinScale { CGFloat zoomScale = self.minimumZoomScale; if (_imageView) { // Zoom image to fill if the aspect ratios are fairly similar CGSize boundsSize = self.bounds.size; CGSize imageSize = self->_imageSize; CGFloat boundsAR = boundsSize.width / boundsSize.height; CGFloat imageAR = imageSize.width / imageSize.height; // the scale needed to perfectly fit the image width-wise CGFloat xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image height-wise CGFloat yScale = boundsSize.height / imageSize.height; // Zooms standard portrait images on a 3.5in screen but not on a 4in screen. if (ABS(boundsAR - imageAR) < 0.17) { zoomScale = MAX(xScale, yScale); // Ensure we don't zoom in or out too far, just in case zoomScale = MIN(MAX(self.minimumZoomScale, zoomScale), self.maximumZoomScale); } } return zoomScale; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return _imageView; } - (DXErrorIndicator *)errorPlaceholder { if (!_errorPlaceholder) { _errorPlaceholder = [[DXErrorIndicator alloc] initWithFrame:CGRectMake(0, 0, 44.0, 44.0)]; _errorPlaceholder.center = self.center; [_errorPlaceholder addTarget:self action:@selector(reloadDisplay) forControlEvents:UIControlEventTouchUpInside]; } return _errorPlaceholder; } - (void)reloadDisplay { self.photo = _photo; } - (void)layoutSubviews { // Position indicators (centre does not seem to work!) if (!_loadingIndicator.hidden) _loadingIndicator.frame = CGRectMake(floorf((self.bounds.size.width - _loadingIndicator.frame.size.width) / 2.), floorf((self.bounds.size.height - _loadingIndicator.frame.size.height) / 2), _loadingIndicator.frame.size.width, _loadingIndicator.frame.size.height); if (_errorPlaceholder) _errorPlaceholder.frame = CGRectMake(floorf((self.bounds.size.width - _errorPlaceholder.frame.size.width) / 2.), floorf((self.bounds.size.height - _errorPlaceholder.frame.size.height) / 2), _errorPlaceholder.frame.size.width, _errorPlaceholder.frame.size.height); // Super [super layoutSubviews]; // Center the image as it becomes smaller than the size of the screen CGSize boundsSize = self.bounds.size; CGRect frameToCenter = _imageView.frame; // Horizontally if (frameToCenter.size.width < boundsSize.width) { frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2.0); } else { frameToCenter.origin.x = 0; } // Vertically if (frameToCenter.size.height < boundsSize.height) { frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2.0); } else { frameToCenter.origin.y = 0; } // Center if (!CGRectEqualToRect(_imageView.frame, frameToCenter)) _imageView.frame = frameToCenter; } - (void)imageView:(UIImageView *)imageView doubleTapDetected:(UITouch *)touch { [self handleDoubleTap:[touch locationInView:imageView]]; } // Background View - (void)view:(UIView *)view singleTapDetected:(UITouch *)touch { // Translate touch location to image view location CGFloat touchX = [touch locationInView:view].x; CGFloat touchY = [touch locationInView:view].y; touchX *= 1/self.zoomScale; touchY *= 1/self.zoomScale; touchX += self.contentOffset.x; touchY += self.contentOffset.y; [self handleSingleTap:CGPointMake(touchX, touchY)]; } - (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch { // Translate touch location to image view location CGFloat touchX = [touch locationInView:view].x; CGFloat touchY = [touch locationInView:view].y; touchX *= 1/self.zoomScale; touchY *= 1/self.zoomScale; touchX += self.contentOffset.x; touchY += self.contentOffset.y; [self handleDoubleTap:CGPointMake(touchX, touchY)]; } - (void)handleSingleTap:(CGPoint)touchPoint { if ([_zoomDelegate respondsToSelector:@selector(zoomingScrollViewSingleTapped:)]) { [_zoomDelegate zoomingScrollViewSingleTapped:self]; } } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { [self setNeedsLayout]; [self layoutIfNeeded]; } - (void)handleDoubleTap:(CGPoint)touchPoint { // Zoom if (self.zoomScale != self.minimumZoomScale && self.zoomScale != [self initialZoomScaleWithMinScale]) { // Zoom out [self setZoomScale:self.minimumZoomScale animated:YES]; } else { // Zoom in to twice the size CGFloat newZoomScale = ((self.maximumZoomScale + self.minimumZoomScale) / 2); CGFloat xsize = self.bounds.size.width / newZoomScale; CGFloat ysize = self.bounds.size.height / newZoomScale; [self zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES]; } } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/UIImage+DXAppleBlur.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (dx_AppleBlur) // apple wwdc session code for the blur - (UIImage *)dx_applyLightEffect; - (UIImage *)dx_applyExtraLightEffect; - (UIImage *)dx_applyDarkEffect; - (UIImage *)dx_applyGrayEffect; - (UIImage *)dx_applyTintEffectWithColor:(UIColor *)tintColor; - (UIImage *)dx_applyBlackEffect; - (UIImage *)dx_applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage; @end @interface UIImage (dx_Light) - (UIImage *)dx_cropImageWithRect:(CGRect)cropRect; - (BOOL)dx_isLight; - (UIColor *)dx_averageColor; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/UIImage+DXAppleBlur.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "UIImage+DXAppleBlur.h" #import <Accelerate/Accelerate.h> @implementation UIImage (dx_AppleBlur) - (UIImage *)dx_applyLightEffect { UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3]; return [self dx_applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyExtraLightEffect { UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyDarkEffect { UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyGrayEffect { UIColor *tintColor = [UIColor colorWithWhite:0.73 alpha:0.73]; return [self dx_applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyBlackEffect { UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73]; return [self dx_applyBlurWithRadius:10.0 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil]; } - (UIImage *)dx_applyTintEffectWithColor:(UIColor *)tintColor { const CGFloat EffectColorAlpha = 0.6; UIColor *effectColor = tintColor; size_t componentCount = CGColorGetNumberOfComponents(tintColor.CGColor); if (componentCount == 2) { CGFloat b; if ([tintColor getWhite:&b alpha:NULL]) { effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha]; } } else { CGFloat r, g, b; if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) { effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha]; } } return [self dx_applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil]; } - (UIImage *)dx_applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage { // check pre-conditions if (self.size.width < 1 || self.size.height < 1) { NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self); return nil; } if (!self.CGImage) { NSLog (@"*** error: image must be backed by a CGImage: %@", self); return nil; } if (maskImage && !maskImage.CGImage) { NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage); return nil; } CGRect imageRect = { CGPointZero, self.size }; UIImage *effectImage = self; BOOL hasBlur = blurRadius > __FLT_EPSILON__; BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__; if (hasBlur || hasSaturationChange) { UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef effectInContext = UIGraphicsGetCurrentContext(); CGContextScaleCTM(effectInContext, 1.0, -1.0); CGContextTranslateCTM(effectInContext, 0, -self.size.height); CGContextDrawImage(effectInContext, imageRect, self.CGImage); vImage_Buffer effectInBuffer; effectInBuffer.data = CGBitmapContextGetData(effectInContext); effectInBuffer.width = CGBitmapContextGetWidth(effectInContext); effectInBuffer.height = CGBitmapContextGetHeight(effectInContext); effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext); UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef effectOutContext = UIGraphicsGetCurrentContext(); vImage_Buffer effectOutBuffer; effectOutBuffer.data = CGBitmapContextGetData(effectOutContext); effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext); effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext); effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext); if (hasBlur) { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale]; uint32_t radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5); if (radius % 2 != 1) { radius += 1; // force radius to be odd so that the three box-blur methodology works. } vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); } BOOL effectImageBuffersAreSwapped = NO; if (hasSaturationChange) { CGFloat s = saturationDeltaFactor; CGFloat floatingPointSaturationMatrix[] = { 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1, }; const int32_t divisor = 256; NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]); int16_t saturationMatrix[matrixSize]; for (NSUInteger i = 0; i < matrixSize; ++i) { saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor); } if (hasBlur) { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags); effectImageBuffersAreSwapped = YES; } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags); } } if (!effectImageBuffersAreSwapped) effectImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (effectImageBuffersAreSwapped) effectImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } // set up output context UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]); CGContextRef outputContext = UIGraphicsGetCurrentContext(); CGContextScaleCTM(outputContext, 1.0, -1.0); CGContextTranslateCTM(outputContext, 0, -self.size.height); // draw base image CGContextDrawImage(outputContext, imageRect, self.CGImage); // draw effect image if (hasBlur) { CGContextSaveGState(outputContext); if (maskImage) { CGContextClipToMask(outputContext, imageRect, maskImage.CGImage); } CGContextDrawImage(outputContext, imageRect, effectImage.CGImage); CGContextRestoreGState(outputContext); } // add in color tint if (tintColor) { CGContextSaveGState(outputContext); CGContextSetFillColorWithColor(outputContext, tintColor.CGColor); CGContextFillRect(outputContext, imageRect); CGContextRestoreGState(outputContext); } // output image is ready UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return outputImage; } @end @implementation UIImage (dx_Light) - (UIImage *)dx_cropImageWithRect:(CGRect)cropRect { if (CGSizeEqualToSize(self.size, CGSizeZero)) return nil; CGFloat scale = [UIScreen mainScreen].scale; cropRect = CGRectMake(cropRect.origin.x * scale, cropRect.origin.y * scale, cropRect.size.width * scale, cropRect.size.height * scale); UIGraphicsBeginImageContextWithOptions(cropRect.size, NO, 0); CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], cropRect); UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); [croppedImage drawInRect:CGRectMake(0, 0, cropRect.size.width, cropRect.size.height)]; UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); return resultImage; } - (BOOL)dx_isLight { BOOL imageIsLight = NO; CGImageRef imageRef = [self CGImage]; CGDataProviderRef dataProviderRef = CGImageGetDataProvider(imageRef); NSData *pixelData = (__bridge_transfer NSData *)CGDataProviderCopyData(dataProviderRef); if ([pixelData length] > 0) { const UInt8 *pixelBytes = [pixelData bytes]; // Whether or not the image format is opaque, the first byte is always the alpha component, followed by RGB. UInt8 pixelR = pixelBytes[1]; UInt8 pixelG = pixelBytes[2]; UInt8 pixelB = pixelBytes[3]; // Calculate the perceived luminance of the pixel; the human eye favors green, followed by red, then blue. double percievedLuminance = 1 - (((0.299 * pixelR) + (0.587 * pixelG) + (0.114 * pixelB)) / 255); imageIsLight = percievedLuminance < 0.5; } return imageIsLight; } - (UIColor *)dx_averageColor { CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); unsigned char rgba[4]; CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage); CGColorSpaceRelease(colorSpace); CGContextRelease(context); if(rgba[3] > 0) { CGFloat alpha = ((CGFloat)rgba[3])/255.0; CGFloat multiplier = alpha/255.0; return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier green:((CGFloat)rgba[1])*multiplier blue:((CGFloat)rgba[2])*multiplier alpha:alpha]; } else { return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0 green:((CGFloat)rgba[1])/255.0 blue:((CGFloat)rgba[2])/255.0 alpha:((CGFloat)rgba[3])/255.0]; } } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/UIView+DXScreenShot.h
C/C++ Header
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (DXScreenShot) - (UIImage *)dx_screenShotImage; - (UIImage *)dx_screenShotImageAfterScreenUpdates:(BOOL)update; - (UIImage *)dx_screenShotImageWithBounds:(CGRect)selfBounds afterScreenUpdates:(BOOL)update; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXPhotoBrowser/Pod/Classes/UIView+DXScreenShot.m
Objective-C
// // DXPhotoBrowser // // Created by xiekw on 15/5/30. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "UIView+DXScreenShot.h" @implementation UIView (DXScreenShot) - (UIImage *)dx_screenShotImageWithBounds:(CGRect)selfBounds afterScreenUpdates:(BOOL)update { UIGraphicsBeginImageContextWithOptions(selfBounds.size, NO, 0); // The ios7 faster screenshot image method if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { [self drawViewHierarchyInRect:CGRectMake(-selfBounds.origin.x, -selfBounds.origin.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) afterScreenUpdates:update]; }else { [self.layer renderInContext:UIGraphicsGetCurrentContext()]; } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } - (UIImage *)dx_screenShotImage { return [self dx_screenShotImageWithBounds:self.bounds afterScreenUpdates:NO]; } - (UIImage *)dx_screenShotImageAfterScreenUpdates:(BOOL)update { return [self dx_screenShotImageWithBounds:self.bounds afterScreenUpdates:update]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h
C/C++ Header
// // Created by Fabrice Aneche on 06/01/14. // Copyright (c) 2014 Dailymotion. All rights reserved. // #import <Foundation/Foundation.h> @interface NSData (ImageContentType) /** * Compute the content type for an image data * * @param data the input data * * @return the content type as string (i.e. image/jpeg, image/gif) */ + (NSString *)sd_contentTypeForImageData:(NSData *)data; @end @interface NSData (ImageContentTypeDeprecated) + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m
Objective-C
// // Created by Fabrice Aneche on 06/01/14. // Copyright (c) 2014 Dailymotion. All rights reserved. // #import "NSData+ImageContentType.h" @implementation NSData (ImageContentType) + (NSString *)sd_contentTypeForImageData:(NSData *)data { uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @"image/jpeg"; case 0x89: return @"image/png"; case 0x47: return @"image/gif"; case 0x49: case 0x4D: return @"image/tiff"; case 0x52: // R as RIFF for WEBP if ([data length] < 12) { return nil; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return @"image/webp"; } return nil; } return nil; } @end @implementation NSData (ImageContentTypeDeprecated) + (NSString *)contentTypeForImageData:(NSData *)data { return [self sd_contentTypeForImageData:data]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDImageCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" typedef NS_ENUM(NSInteger, SDImageCacheType) { /** * The image wasn't available the SDWebImage caches, but was downloaded from the web. */ SDImageCacheTypeNone, /** * The image was obtained from the disk cache. */ SDImageCacheTypeDisk, /** * The image was obtained from the memory cache. */ SDImageCacheTypeMemory }; typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); /** * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed * asynchronous so it doesn’t add unnecessary latency to the UI. */ @interface SDImageCache : NSObject /** * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; /** * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** * The maximum number of objects the cache should hold. */ @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; /** * The maximum length of time to keep an image in the cache, in seconds */ @property (assign, nonatomic) NSInteger maxCacheAge; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxCacheSize; /** * Returns global shared cache instance * * @return SDImageCache global instance */ + (SDImageCache *)sharedImageCache; /** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */ - (id)initWithNamespace:(NSString *)ns; /** * Init a new cache store with a specific namespace and directory * * @param ns The namespace to use for this cache store * @param directory Directory to cache disk images in */ - (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory; -(NSString *)makeDiskCachePath:(NSString*)fullNamespace; /** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */ - (void)addReadOnlyCachePath:(NSString *)path; /** * Store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage * @param imageData The image data as returned by the server, this representation will be used for disk storage * instead of converting the given image object into a storable/compressed image format in order * to save quality and CPU * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image */ - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; /** * Query the memory cache synchronously. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; /** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; /** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key */ - (void)removeImageForKey:(NSString *)key; /** * Remove the image from memory and disk cache asynchronously * * @param key The unique image cache key * @param completion An block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; /** * Remove the image from memory and optionally disk cache asynchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES */ - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; /** * Remove the image from memory and optionally disk cache asynchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES * @param completion An block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; /** * Clear all memory cached images */ - (void)clearMemory; /** * Clear all disk cached images. Non-blocking method - returns immediately. * @param completion An block that should be executed after cache expiration completes (optional) */ - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; /** * Clear all disk cached images * @see clearDiskOnCompletion: */ - (void)clearDisk; /** * Remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */ - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; /** * Remove all expired cached image from disk * @see cleanDiskWithCompletionBlock: */ - (void)cleanDisk; /** * Get the size used by the disk cache */ - (NSUInteger)getSize; /** * Get the number of images in the disk cache */ - (NSUInteger)getDiskCount; /** * Asynchronously calculate the disk cache's size. */ - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; /** * Async check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * @param completionBlock the block to be executed when the check is done. * @note the completion block will be always executed on the main queue */ - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * * @return YES if an image exists for the given key */ - (BOOL)diskImageExistsWithKey:(NSString *)key; /** * Get the cache path for a certain key (needs the cache path root folder) * * @param key the key (can be obtained from url using cacheKeyForURL) * @param path the cach path root folder * * @return the cache path */ - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; /** * Get the default cache path for a certain key * * @param key the key (can be obtained from url using cacheKeyForURL) * * @return the default cache path */ - (NSString *)defaultCachePathForKey:(NSString *)key; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDImageCache.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDImageCache.h" #import "SDWebImageDecoder.h" #import "UIImage+MultiFormat.h" #import <CommonCrypto/CommonDigest.h> // See https://github.com/rs/SDWebImage/pull/1141 for discussion @interface AutoPurgeCache : NSCache @end @implementation AutoPurgeCache - (id)init { self = [super init]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; } @end static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week // PNG signature bytes and data (below) static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; static NSData *kPNGSignatureData = nil; BOOL ImageDataHasPNGPreffix(NSData *data); BOOL ImageDataHasPNGPreffix(NSData *data) { NSUInteger pngSignatureLength = [kPNGSignatureData length]; if ([data length] >= pngSignatureLength) { if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { return YES; } } return NO; } FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) { return image.size.height * image.size.width * image.scale * image.scale; } @interface SDImageCache () @property (strong, nonatomic) NSCache *memCache; @property (strong, nonatomic) NSString *diskCachePath; @property (strong, nonatomic) NSMutableArray *customPaths; @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; @end @implementation SDImageCache { NSFileManager *_fileManager; } + (SDImageCache *)sharedImageCache { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (id)init { return [self initWithNamespace:@"default"]; } - (id)initWithNamespace:(NSString *)ns { NSString *path = [self makeDiskCachePath:ns]; return [self initWithNamespace:ns diskCacheDirectory:path]; } - (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory { if ((self = [super init])) { NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; // initialise PNG signature data kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; // Create IO serial queue _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); // Init default values _maxCacheAge = kDefaultCacheMaxCacheAge; // Init the memory cache _memCache = [[AutoPurgeCache alloc] init]; _memCache.name = fullNamespace; // Init the disk cache if (directory != nil) { _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace]; } else { NSString *path = [self makeDiskCachePath:ns]; _diskCachePath = path; } // Set decompression to YES _shouldDecompressImages = YES; dispatch_sync(_ioQueue, ^{ _fileManager = [NSFileManager new]; }); #if TARGET_OS_IPHONE // Subscribe to app events [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanDisk) name:UIApplicationWillTerminateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundCleanDisk) name:UIApplicationDidEnterBackgroundNotification object:nil]; #endif } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; SDDispatchQueueRelease(_ioQueue); } - (void)addReadOnlyCachePath:(NSString *)path { if (!self.customPaths) { self.customPaths = [NSMutableArray new]; } if (![self.customPaths containsObject:path]) { [self.customPaths addObject:path]; } } - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { NSString *filename = [self cachedFileNameForKey:key]; return [path stringByAppendingPathComponent:filename]; } - (NSString *)defaultCachePathForKey:(NSString *)key { return [self cachePathForKey:key inPath:self.diskCachePath]; } #pragma mark SDImageCache (private) - (NSString *)cachedFileNameForKey:(NSString *)key { const char *str = [key UTF8String]; if (str == NULL) { str = ""; } unsigned char r[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), r); NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; return filename; } #pragma mark ImageCache // Init the disk cache -(NSString *)makeDiskCachePath:(NSString*)fullNamespace{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [paths[0] stringByAppendingPathComponent:fullNamespace]; } - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { if (!image || !key) { return; } NSUInteger cost = SDCacheCostForImage(image); [self.memCache setObject:image forKey:key cost:cost]; if (toDisk) { dispatch_async(self.ioQueue, ^{ NSData *data = imageData; if (image && (recalculate || !data)) { #if TARGET_OS_IPHONE // We need to determine if the image is a PNG or a JPEG // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) // The first eight bytes of a PNG file always contain the following (decimal) values: // 137 80 78 71 13 10 26 10 // If the imageData is nil (i.e. if trying to save a UIImage directly or the image was transformed on download) // and the image has an alpha channel, we will consider it PNG to avoid losing the transparency int alphaInfo = CGImageGetAlphaInfo(image.CGImage); BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || alphaInfo == kCGImageAlphaNoneSkipFirst || alphaInfo == kCGImageAlphaNoneSkipLast); BOOL imageIsPng = hasAlpha; // But if we have an image data, we will look at the preffix if ([imageData length] >= [kPNGSignatureData length]) { imageIsPng = ImageDataHasPNGPreffix(imageData); } if (imageIsPng) { data = UIImagePNGRepresentation(image); } else { data = UIImageJPEGRepresentation(image, (CGFloat)1.0); } #else data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; #endif } if (data) { if (![_fileManager fileExistsAtPath:_diskCachePath]) { [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; } [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; } }); } } - (void)storeImage:(UIImage *)image forKey:(NSString *)key { [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; } - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; } - (BOOL)diskImageExistsWithKey:(NSString *)key { BOOL exists = NO; // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely. exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]]; return exists; } - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { dispatch_async(_ioQueue, ^{ BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(exists); }); } }); } - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { return [self.memCache objectForKey:key]; } - (UIImage *)imageFromDiskCacheForKey:(NSString *)key { // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { return image; } // Second check the disk cache... UIImage *diskImage = [self diskImageForKey:key]; if (diskImage) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } return diskImage; } - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { NSString *defaultPath = [self defaultCachePathForKey:key]; NSData *data = [NSData dataWithContentsOfFile:defaultPath]; if (data) { return data; } NSArray *customPaths = [self.customPaths copy]; for (NSString *path in customPaths) { NSString *filePath = [self cachePathForKey:key inPath:path]; NSData *imageData = [NSData dataWithContentsOfFile:filePath]; if (imageData) { return imageData; } } return nil; } - (UIImage *)diskImageForKey:(NSString *)key { NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; if (data) { UIImage *image = [UIImage sd_imageWithData:data]; image = [self scaledImageForKey:key image:image]; if (self.shouldDecompressImages) { image = [UIImage decodedImageWithImage:image]; } return image; } else { return nil; } } - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { return SDScaledImageForKey(key, image); } - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { if (!doneBlock) { return nil; } if (!key) { doneBlock(nil, SDImageCacheTypeNone); return nil; } // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { doneBlock(image, SDImageCacheTypeMemory); return nil; } NSOperation *operation = [NSOperation new]; dispatch_async(self.ioQueue, ^{ if (operation.isCancelled) { return; } @autoreleasepool { UIImage *diskImage = [self diskImageForKey:key]; if (diskImage) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } dispatch_async(dispatch_get_main_queue(), ^{ doneBlock(diskImage, SDImageCacheTypeDisk); }); } }); return operation; } - (void)removeImageForKey:(NSString *)key { [self removeImageForKey:key withCompletion:nil]; } - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion { [self removeImageForKey:key fromDisk:YES withCompletion:completion]; } - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil]; } - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion { if (key == nil) { return; } [self.memCache removeObjectForKey:key]; if (fromDisk) { dispatch_async(self.ioQueue, ^{ [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; if (completion) { dispatch_async(dispatch_get_main_queue(), ^{ completion(); }); } }); } else if (completion){ completion(); } } - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { self.memCache.totalCostLimit = maxMemoryCost; } - (NSUInteger)maxMemoryCost { return self.memCache.totalCostLimit; } - (NSUInteger)maxMemoryCountLimit { return self.memCache.countLimit; } - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit { self.memCache.countLimit = maxCountLimit; } - (void)clearMemory { [self.memCache removeAllObjects]; } - (void)clearDisk { [self clearDiskOnCompletion:nil]; } - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion { dispatch_async(self.ioQueue, ^{ [_fileManager removeItemAtPath:self.diskCachePath error:nil]; [_fileManager createDirectoryAtPath:self.diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; if (completion) { dispatch_async(dispatch_get_main_queue(), ^{ completion(); }); } }); } - (void)cleanDisk { [self cleanDiskWithCompletionBlock:nil]; } - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock { dispatch_async(self.ioQueue, ^{ NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; // This enumerator prefetches useful properties for our cache files. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:resourceKeys options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL]; NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; NSUInteger currentCacheSize = 0; // Enumerate all of the files in the cache directory. This loop has two purposes: // // 1. Removing files that are older than the expiration date. // 2. Storing file attributes for the size-based cleanup pass. NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; for (NSURL *fileURL in fileEnumerator) { NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; // Skip directories. if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { continue; } // Remove files that are older than the expiration date; NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { [urlsToDelete addObject:fileURL]; continue; } // Store a reference to this file and account for its total size. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; [cacheFiles setObject:resourceValues forKey:fileURL]; } for (NSURL *fileURL in urlsToDelete) { [_fileManager removeItemAtURL:fileURL error:nil]; } // If our remaining disk cache exceeds a configured maximum size, perform a second // size-based cleanup pass. We delete the oldest files first. if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { // Target half of our maximum cache size for this cleanup pass. const NSUInteger desiredCacheSize = self.maxCacheSize / 2; // Sort the remaining cache files by their last modification time (oldest first). NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(id obj1, id obj2) { return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; }]; // Delete files until we fall below our desired cache size. for (NSURL *fileURL in sortedFiles) { if ([_fileManager removeItemAtURL:fileURL error:nil]) { NSDictionary *resourceValues = cacheFiles[fileURL]; NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; if (currentCacheSize < desiredCacheSize) { break; } } } } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(); }); } }); } - (void)backgroundCleanDisk { Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Clean up any unfinished task business by marking where you // stopped or ending the task outright. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. [self cleanDiskWithCompletionBlock:^{ [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; } - (NSUInteger)getSize { __block NSUInteger size = 0; dispatch_sync(self.ioQueue, ^{ NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; for (NSString *fileName in fileEnumerator) { NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; size += [attrs fileSize]; } }); return size; } - (NSUInteger)getDiskCount { __block NSUInteger count = 0; dispatch_sync(self.ioQueue, ^{ NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; count = [[fileEnumerator allObjects] count]; }); return count; } - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock { NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; dispatch_async(self.ioQueue, ^{ NSUInteger fileCount = 0; NSUInteger totalSize = 0; NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:@[NSFileSize] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL]; for (NSURL *fileURL in fileEnumerator) { NSNumber *fileSize; [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; totalSize += [fileSize unsignedIntegerValue]; fileCount += 1; } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(fileCount, totalSize); }); } }); } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Jamie Pinkham * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <TargetConditionals.h> #ifdef __OBJC_GC__ #error SDWebImage does not support Objective-C Garbage Collection #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 #error SDWebImage doesn't support Deployement Target version < 5.0 #endif #if !TARGET_OS_IPHONE #import <AppKit/AppKit.h> #ifndef UIImage #define UIImage NSImage #endif #ifndef UIImageView #define UIImageView NSImageView #endif #else #import <UIKit/UIKit.h> #endif #ifndef NS_ENUM #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type #endif #ifndef NS_OPTIONS #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type #endif #if OS_OBJECT_USE_OBJC #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) #define SDDispatchQueueSetterSementics strong #else #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) (dispatch_release(q)) #define SDDispatchQueueSetterSementics assign #endif extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); typedef void(^SDWebImageNoParamsBlock)(); extern NSString *const SDWebImageErrorDomain; #define dispatch_main_sync_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_sync(dispatch_get_main_queue(), block);\ } #define dispatch_main_async_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ }
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m
Objective-C
// // SDWebImageCompat.m // SDWebImage // // Created by Olivier Poitrey on 11/12/12. // Copyright (c) 2012 Dailymotion. All rights reserved. // #import "SDWebImageCompat.h" #if !__has_feature(objc_arc) #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag #endif inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { if (!image) { return nil; } if ([image.images count] > 0) { NSMutableArray *scaledImages = [NSMutableArray array]; for (UIImage *tempImage in image.images) { [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; } return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; } else { if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { CGFloat scale = 1.0; if (key.length >= 8) { NSRange range = [key rangeOfString:@"@2x."]; if (range.location != NSNotFound) { scale = 2.0; } range = [key rangeOfString:@"@3x."]; if (range.location != NSNotFound) { scale = 3.0; } } UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; image = scaledImage; } return image; } } NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain";
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * Created by james <https://github.com/mystcolor> on 9/28/11. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" @interface UIImage (ForceDecode) + (UIImage *)decodedImageWithImage:(UIImage *)image; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * Created by james <https://github.com/mystcolor> on 9/28/11. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDecoder.h" @implementation UIImage (ForceDecode) + (UIImage *)decodedImageWithImage:(UIImage *)image { if (image.images) { // Do not decode animated images return image; } CGImageRef imageRef = image.CGImage; CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || infoMask == kCGImageAlphaNoneSkipFirst || infoMask == kCGImageAlphaNoneSkipLast); // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. // https://developer.apple.com/library/mac/#qa/qa1037/_index.html if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { // Unset the old alpha info. bitmapInfo &= ~kCGBitmapAlphaInfoMask; // Set noneSkipFirst. bitmapInfo |= kCGImageAlphaNoneSkipFirst; } // Some PNGs tell us they have alpha but only 3 components. Odd. else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { // Unset the old alpha info. bitmapInfo &= ~kCGBitmapAlphaInfoMask; bitmapInfo |= kCGImageAlphaPremultipliedFirst; } // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), 0, colorSpace, bitmapInfo); CGColorSpaceRelease(colorSpace); // If failed, return undecompressed image if (!context) return image; CGContextDrawImage(context, imageRect, imageRef); CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); CGContextRelease(context); UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(decompressedImageRef); return decompressedImage; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { SDWebImageDownloaderLowPriority = 1 << 0, SDWebImageDownloaderProgressiveDownload = 1 << 1, /** * By default, request prevent the of NSURLCache. With this flag, NSURLCache * is used with default policies. */ SDWebImageDownloaderUseNSURLCache = 1 << 2, /** * Call completion block with nil image/imageData if the image was read from NSURLCache * (to be combined with `SDWebImageDownloaderUseNSURLCache`). */ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageDownloaderContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageDownloaderHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL ceriticates. * Useful for testing purposes. Use with caution in production. */ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, /** * Put the image in the high priority queue. */ SDWebImageDownloaderHighPriority = 1 << 7, }; typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { /** * Default value. All download operations will execute in queue style (first-in-first-out). */ SDWebImageDownloaderFIFOExecutionOrder, /** * All download operations will execute in stack style (last-in-first-out). */ SDWebImageDownloaderLIFOExecutionOrder }; extern NSString *const SDWebImageDownloadStartNotification; extern NSString *const SDWebImageDownloadStopNotification; typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); /** * Asynchronous downloader dedicated and optimized for image loading. */ @interface SDWebImageDownloader : NSObject /** * Decompressing images that are downloaded and cached can improve peformance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; @property (assign, nonatomic) NSInteger maxConcurrentDownloads; /** * Shows the current amount of downloads that still need to be downloaded */ @property (readonly, nonatomic) NSUInteger currentDownloadCount; /** * The timeout value (in seconds) for the download operation. Default: 15.0. */ @property (assign, nonatomic) NSTimeInterval downloadTimeout; /** * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. */ @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; /** * Singleton method, returns the shared instance * * @return global shared instance of downloader class */ + (SDWebImageDownloader *)sharedDownloader; /** * Set username */ @property (strong, nonatomic) NSString *username; /** * Set password */ @property (strong, nonatomic) NSString *password; /** * Set filter to pick headers for downloading image HTTP request. * * This block will be invoked for each downloading image request, returned * NSDictionary will be used as headers in corresponding HTTP request. */ @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; /** * Set a value for a HTTP header to be appended to each download HTTP request. * * @param value The value for the header field. Use `nil` value to remove the header. * @param field The name of the header field to set. */ - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; /** * Returns the value of the specified HTTP header field. * * @return The value associated with the header field field, or `nil` if there is no corresponding header field. */ - (NSString *)valueForHTTPHeaderField:(NSString *)field; /** * Sets a subclass of `SDWebImageDownloaderOperation` as the default * `NSOperation` to be used each time SDWebImage constructs a request * operation to download an image. * * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. */ - (void)setOperationClass:(Class)operationClass; /** * Creates a SDWebImageDownloader async downloader instance with a given URL * * The delegate will be informed when the image is finish downloaded or an error has happen. * * @see SDWebImageDownloaderDelegate * * @param url The URL to the image to download * @param options The options to be used for this download * @param progressBlock A block called repeatedly while the image is downloading * @param completedBlock A block called once the download is completed. * If the download succeeded, the image parameter is set, in case of error, * error parameter is set with the error. The last parameter is always YES * if SDWebImageDownloaderProgressiveDownload isn't use. With the * SDWebImageDownloaderProgressiveDownload option, this block is called * repeatedly with the partial image object and the finished argument set to NO * before to be called a last time with the full image and finished argument * set to YES. In case of error, the finished argument is always YES. * * @return A cancellable SDWebImageOperation */ - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock; /** * Sets the download queue suspension state */ - (void)setSuspended:(BOOL)suspended; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDownloader.h" #import "SDWebImageDownloaderOperation.h" #import <ImageIO/ImageIO.h> static NSString *const kProgressCallbackKey = @"progress"; static NSString *const kCompletedCallbackKey = @"completed"; @interface SDWebImageDownloader () @property (strong, nonatomic) NSOperationQueue *downloadQueue; @property (weak, nonatomic) NSOperation *lastAddedOperation; @property (assign, nonatomic) Class operationClass; @property (strong, nonatomic) NSMutableDictionary *URLCallbacks; @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; // This queue is used to serialize the handling of the network responses of all the download operation in a single queue @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; @end @implementation SDWebImageDownloader + (void)initialize { // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import if (NSClassFromString(@"SDNetworkActivityIndicator")) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; #pragma clang diagnostic pop // Remove observer in case it was previously added. [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:activityIndicator selector:NSSelectorFromString(@"startActivity") name:SDWebImageDownloadStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:activityIndicator selector:NSSelectorFromString(@"stopActivity") name:SDWebImageDownloadStopNotification object:nil]; } } + (SDWebImageDownloader *)sharedDownloader { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (id)init { if ((self = [super init])) { _operationClass = [SDWebImageDownloaderOperation class]; _shouldDecompressImages = YES; _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; _downloadQueue = [NSOperationQueue new]; _downloadQueue.maxConcurrentOperationCount = 6; _URLCallbacks = [NSMutableDictionary new]; #ifdef SD_WEBP _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; #else _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; #endif _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); _downloadTimeout = 15.0; } return self; } - (void)dealloc { [self.downloadQueue cancelAllOperations]; SDDispatchQueueRelease(_barrierQueue); } - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { if (value) { self.HTTPHeaders[field] = value; } else { [self.HTTPHeaders removeObjectForKey:field]; } } - (NSString *)valueForHTTPHeaderField:(NSString *)field { return self.HTTPHeaders[field]; } - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; } - (NSUInteger)currentDownloadCount { return _downloadQueue.operationCount; } - (NSInteger)maxConcurrentDownloads { return _downloadQueue.maxConcurrentOperationCount; } - (void)setOperationClass:(Class)operationClass { _operationClass = operationClass ?: [SDWebImageDownloaderOperation class]; } - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { __block SDWebImageDownloaderOperation *operation; __weak __typeof(self)wself = self; [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ NSTimeInterval timeoutInterval = wself.downloadTimeout; if (timeoutInterval == 0.0) { timeoutInterval = 15.0; } // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); request.HTTPShouldUsePipelining = YES; if (wself.headersFilter) { request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); } else { request.allHTTPHeaderFields = wself.HTTPHeaders; } operation = [[wself.operationClass alloc] initWithRequest:request options:options progress:^(NSInteger receivedSize, NSInteger expectedSize) { SDWebImageDownloader *sself = wself; if (!sself) return; __block NSArray *callbacksForURL; dispatch_sync(sself.barrierQueue, ^{ callbacksForURL = [sself.URLCallbacks[url] copy]; }); for (NSDictionary *callbacks in callbacksForURL) { SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; if (callback) callback(receivedSize, expectedSize); } } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { SDWebImageDownloader *sself = wself; if (!sself) return; __block NSArray *callbacksForURL; dispatch_barrier_sync(sself.barrierQueue, ^{ callbacksForURL = [sself.URLCallbacks[url] copy]; if (finished) { [sself.URLCallbacks removeObjectForKey:url]; } }); for (NSDictionary *callbacks in callbacksForURL) { SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; if (callback) callback(image, data, error, finished); } } cancelled:^{ SDWebImageDownloader *sself = wself; if (!sself) return; dispatch_barrier_async(sself.barrierQueue, ^{ [sself.URLCallbacks removeObjectForKey:url]; }); }]; operation.shouldDecompressImages = wself.shouldDecompressImages; if (wself.username && wself.password) { operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; } if (options & SDWebImageDownloaderHighPriority) { operation.queuePriority = NSOperationQueuePriorityHigh; } else if (options & SDWebImageDownloaderLowPriority) { operation.queuePriority = NSOperationQueuePriorityLow; } [wself.downloadQueue addOperation:operation]; if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { // Emulate LIFO execution order by systematically adding new operations as last operation's dependency [wself.lastAddedOperation addDependency:operation]; wself.lastAddedOperation = operation; } }]; return operation; } - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. if (url == nil) { if (completedBlock != nil) { completedBlock(nil, nil, nil, NO); } return; } dispatch_barrier_sync(self.barrierQueue, ^{ BOOL first = NO; if (!self.URLCallbacks[url]) { self.URLCallbacks[url] = [NSMutableArray new]; first = YES; } // Handle single download of simultaneous download request for the same URL NSMutableArray *callbacksForURL = self.URLCallbacks[url]; NSMutableDictionary *callbacks = [NSMutableDictionary new]; if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; [callbacksForURL addObject:callbacks]; self.URLCallbacks[url] = callbacksForURL; if (first) { createCallback(); } }); } - (void)setSuspended:(BOOL)suspended { [self.downloadQueue setSuspended:suspended]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageDownloader.h" #import "SDWebImageOperation.h" extern NSString *const SDWebImageDownloadStartNotification; extern NSString *const SDWebImageDownloadReceiveResponseNotification; extern NSString *const SDWebImageDownloadStopNotification; extern NSString *const SDWebImageDownloadFinishNotification; @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation> /** * The request used by the operation's connection. */ @property (strong, nonatomic, readonly) NSURLRequest *request; @property (assign, nonatomic) BOOL shouldDecompressImages; /** * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. * * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. */ @property (nonatomic, assign) BOOL shouldUseCredentialStorage; /** * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. * * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. */ @property (nonatomic, strong) NSURLCredential *credential; /** * The SDWebImageDownloaderOptions for the receiver. */ @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; /** * The expected size of data. */ @property (assign, nonatomic) NSInteger expectedSize; /** * The response returned by the operation's connection. */ @property (strong, nonatomic) NSURLResponse *response; /** * Initializes a `SDWebImageDownloaderOperation` object * * @see SDWebImageDownloaderOperation * * @param request the URL request * @param options downloader options * @param progressBlock the block executed when a new chunk of data arrives. * @note the progress block is executed on a background queue * @param completedBlock the block executed when the download is done. * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue * @param cancelBlock the block executed if the download (operation) is cancelled * * @return the initialized instance */ - (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock cancelled:(SDWebImageNoParamsBlock)cancelBlock; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDownloaderOperation.h" #import "SDWebImageDecoder.h" #import "UIImage+MultiFormat.h" #import <ImageIO/ImageIO.h> #import "SDWebImageManager.h" NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; @interface SDWebImageDownloaderOperation () <NSURLConnectionDataDelegate> @property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; @property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; @property (assign, nonatomic, getter = isExecuting) BOOL executing; @property (assign, nonatomic, getter = isFinished) BOOL finished; @property (strong, nonatomic) NSMutableData *imageData; @property (strong, nonatomic) NSURLConnection *connection; @property (strong, atomic) NSThread *thread; #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; #endif @end @implementation SDWebImageDownloaderOperation { size_t width, height; UIImageOrientation orientation; BOOL responseFromCached; } @synthesize executing = _executing; @synthesize finished = _finished; - (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock cancelled:(SDWebImageNoParamsBlock)cancelBlock { if ((self = [super init])) { _request = request; _shouldDecompressImages = YES; _shouldUseCredentialStorage = YES; _options = options; _progressBlock = [progressBlock copy]; _completedBlock = [completedBlock copy]; _cancelBlock = [cancelBlock copy]; _executing = NO; _finished = NO; _expectedSize = 0; responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called } return self; } - (void)start { @synchronized (self) { if (self.isCancelled) { self.finished = YES; [self reset]; return; } #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 Class UIApplicationClass = NSClassFromString(@"UIApplication"); BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { __weak __typeof__ (self) wself = self; UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof (wself) sself = wself; if (sself) { [sself cancel]; [app endBackgroundTask:sself.backgroundTaskId]; sself.backgroundTaskId = UIBackgroundTaskInvalid; } }]; } #endif self.executing = YES; self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; self.thread = [NSThread currentThread]; } [self.connection start]; if (self.connection) { if (self.progressBlock) { self.progressBlock(0, NSURLResponseUnknownLength); } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; }); if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { // Make sure to run the runloop in our background thread so it can process downloaded data // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); } else { CFRunLoopRun(); } if (!self.isFinished) { [self.connection cancel]; [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; } } else { if (self.completedBlock) { self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); } } #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } if (self.backgroundTaskId != UIBackgroundTaskInvalid) { UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; [app endBackgroundTask:self.backgroundTaskId]; self.backgroundTaskId = UIBackgroundTaskInvalid; } #endif } - (void)cancel { @synchronized (self) { if (self.thread) { [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; } else { [self cancelInternal]; } } } - (void)cancelInternalAndStop { if (self.isFinished) return; [self cancelInternal]; CFRunLoopStop(CFRunLoopGetCurrent()); } - (void)cancelInternal { if (self.isFinished) return; [super cancel]; if (self.cancelBlock) self.cancelBlock(); if (self.connection) { [self.connection cancel]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); // As we cancelled the connection, its callback won't be called and thus won't // maintain the isFinished and isExecuting flags. if (self.isExecuting) self.executing = NO; if (!self.isFinished) self.finished = YES; } [self reset]; } - (void)done { self.finished = YES; self.executing = NO; [self reset]; } - (void)reset { self.cancelBlock = nil; self.completedBlock = nil; self.progressBlock = nil; self.connection = nil; self.imageData = nil; self.thread = nil; } - (void)setFinished:(BOOL)finished { [self willChangeValueForKey:@"isFinished"]; _finished = finished; [self didChangeValueForKey:@"isFinished"]; } - (void)setExecuting:(BOOL)executing { [self willChangeValueForKey:@"isExecuting"]; _executing = executing; [self didChangeValueForKey:@"isExecuting"]; } - (BOOL)isConcurrent { return YES; } #pragma mark NSURLConnection (delegate) - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //'304 Not Modified' is an exceptional one if (![response respondsToSelector:@selector(statusCode)] || ([((NSHTTPURLResponse *)response) statusCode] < 400 && [((NSHTTPURLResponse *)response) statusCode] != 304)) { NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; self.expectedSize = expected; if (self.progressBlock) { self.progressBlock(0, expected); } self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; self.response = response; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self]; }); } else { NSUInteger code = [((NSHTTPURLResponse *)response) statusCode]; //This is the case when server returns '304 Not Modified'. It means that remote image is not changed. //In case of 304 we need just cancel the operation and return cached image from the cache. if (code == 304) { [self cancelInternal]; } else { [self.connection cancel]; } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); if (self.completedBlock) { self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); } CFRunLoopStop(CFRunLoopGetCurrent()); [self done]; } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.imageData appendData:data]; if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ // Thanks to the author @Nyx0uf // Get the total bytes downloaded const NSInteger totalSize = self.imageData.length; // Update the data source, we must pass ALL the data, not just the new bytes CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL); if (width + height == 0) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { NSInteger orientationValue = -1; CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); if (val) CFNumberGetValue(val, kCFNumberLongType, &height); val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); if (val) CFNumberGetValue(val, kCFNumberLongType, &width); val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); CFRelease(properties); // When we draw to Core Graphics, we lose orientation information, // which means the image below born of initWithCGIImage will be // oriented incorrectly sometimes. (Unlike the image born of initWithData // in connectionDidFinishLoading.) So save it here and pass it on later. orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; } } if (width + height > 0 && totalSize < self.expectedSize) { // Create the image CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); #ifdef TARGET_OS_IPHONE // Workaround for iOS anamorphic image if (partialImageRef) { const size_t partialHeight = CGImageGetHeight(partialImageRef); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); if (bmContext) { CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); CGImageRelease(partialImageRef); partialImageRef = CGBitmapContextCreateImage(bmContext); CGContextRelease(bmContext); } else { CGImageRelease(partialImageRef); partialImageRef = nil; } } #endif if (partialImageRef) { UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; UIImage *scaledImage = [self scaledImageForKey:key image:image]; if (self.shouldDecompressImages) { image = [UIImage decodedImageWithImage:scaledImage]; } else { image = scaledImage; } CGImageRelease(partialImageRef); dispatch_main_sync_safe(^{ if (self.completedBlock) { self.completedBlock(image, nil, nil, NO); } }); } } CFRelease(imageSource); } if (self.progressBlock) { self.progressBlock(self.imageData.length, self.expectedSize); } } + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { switch (value) { case 1: return UIImageOrientationUp; case 3: return UIImageOrientationDown; case 8: return UIImageOrientationLeft; case 6: return UIImageOrientationRight; case 2: return UIImageOrientationUpMirrored; case 4: return UIImageOrientationDownMirrored; case 5: return UIImageOrientationLeftMirrored; case 7: return UIImageOrientationRightMirrored; default: return UIImageOrientationUp; } } - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { return SDScaledImageForKey(key, image); } - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; @synchronized(self) { CFRunLoopStop(CFRunLoopGetCurrent()); self.thread = nil; self.connection = nil; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:self]; }); } if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) { responseFromCached = NO; } if (completionBlock) { if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { completionBlock(nil, nil, nil, YES); } else if (self.imageData) { UIImage *image = [UIImage sd_imageWithData:self.imageData]; NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; image = [self scaledImageForKey:key image:image]; // Do not force decoding animated GIFs if (!image.images) { if (self.shouldDecompressImages) { image = [UIImage decodedImageWithImage:image]; } } if (CGSizeEqualToSize(image.size, CGSizeZero)) { completionBlock(nil, nil, [NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); } else { completionBlock(image, self.imageData, nil, YES); } } else { completionBlock(nil, nil, [NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}], YES); } } self.completionBlock = nil; [self done]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { @synchronized(self) { CFRunLoopStop(CFRunLoopGetCurrent()); self.thread = nil; self.connection = nil; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); } if (self.completedBlock) { self.completedBlock(nil, nil, error, YES); } self.completionBlock = nil; [self done]; } - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { responseFromCached = NO; // If this method is called, it means the response wasn't read from cache if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { // Prevents caching of responses return nil; } else { return cachedResponse; } } - (BOOL)shouldContinueWhenAppEntersBackground { return self.options & SDWebImageDownloaderContinueInBackground; } - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { return self.shouldUseCredentialStorage; } - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates) && [challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) { [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge]; } else { NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } } else { if ([challenge previousFailureCount] == 0) { if (self.credential) { [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageManager.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" #import "SDWebImageDownloader.h" #import "SDImageCache.h" typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { /** * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. * This flag disable this blacklisting. */ SDWebImageRetryFailed = 1 << 0, /** * By default, image downloads are started during UI interactions, this flags disable this feature, * leading to delayed download on UIScrollView deceleration for instance. */ SDWebImageLowPriority = 1 << 1, /** * This flag disables on-disk caching */ SDWebImageCacheMemoryOnly = 1 << 2, /** * This flag enables progressive download, the image is displayed progressively during download as a browser would do. * By default, the image is only displayed once completely downloaded. */ SDWebImageProgressiveDownload = 1 << 3, /** * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. * * Use this flag only if you can't make your URLs static with embeded cache busting parameter. */ SDWebImageRefreshCached = 1 << 4, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageContinueInBackground = 1 << 5, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageHandleCookies = 1 << 6, /** * Enable to allow untrusted SSL ceriticates. * Useful for testing purposes. Use with caution in production. */ SDWebImageAllowInvalidSSLCertificates = 1 << 7, /** * By default, image are loaded in the order they were queued. This flag move them to * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which * could take a while). */ SDWebImageHighPriority = 1 << 8, /** * By default, placeholder images are loaded while the image is loading. This flag will delay the loading * of the placeholder image until after the image has finished loading. */ SDWebImageDelayPlaceholder = 1 << 9, /** * We usually don't call transformDownloadedImage delegate method on animated images, * as most transformation code would mangle it. * Use this flag to transform them anyway. */ SDWebImageTransformAnimatedImage = 1 << 10, /** * By default, image is added to the imageView after download. But in some cases, we want to * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) * Use this flag if you want to manually set the image in the completion when success */ SDWebImageAvoidAutoSetImage = 1 << 11 }; typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); @class SDWebImageManager; @protocol SDWebImageManagerDelegate <NSObject> @optional /** * Controls which image should be downloaded when the image is not found in the cache. * * @param imageManager The current `SDWebImageManager` * @param imageURL The url of the image to be downloaded * * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. */ - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; /** * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. * NOTE: This method is called from a global queue in order to not to block the main thread. * * @param imageManager The current `SDWebImageManager` * @param image The image to transform * @param imageURL The url of the image to transform * * @return The transformed image object. */ - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; @end /** * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). * You can use this class directly to benefit from web image downloading with caching in another context than * a UIView. * * Here is a simple example of how to use SDWebImageManager: * * @code SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadImageWithURL:imageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (image) { // do something with image } }]; * @endcode */ @interface SDWebImageManager : NSObject @property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly) SDImageCache *imageCache; @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; /** * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can * be used to remove dynamic part of an image URL. * * The following example sets a filter in the application delegate that will remove any query-string from the * URL before to use it as a cache key: * * @code [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; return [url absoluteString]; }]; * @endcode */ @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; /** * Returns global SDWebImageManager instance. * * @return SDWebImageManager shared instance */ + (SDWebImageManager *)sharedManager; /** * Downloads the image at the given URL if not present in cache or return the cached version otherwise. * * @param url The URL to the image * @param options A mask to specify options to use for this request * @param progressBlock A block called while image is downloading * @param completedBlock A block called when operation has been completed. * * This parameter is required. * * This block has no return value and takes the requested UIImage as first parameter. * In case of error the image parameter is nil and the second parameter may contain an NSError. * * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache * or from the memory cache or from the network. * * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the * block is called a last time with the full image and the last parameter set to YES. * * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation */ - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; /** * Saves image to cache for given URL * * @param image The image to cache * @param url The URL to the image * */ - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; /** * Cancel all current opreations */ - (void)cancelAll; /** * Check one or more operations running */ - (BOOL)isRunning; /** * Check if image has already been cached * * @param url image url * * @return if the image was already cached */ - (BOOL)cachedImageExistsForURL:(NSURL *)url; /** * Check if image has already been cached on disk only * * @param url image url * * @return if the image was already cached (disk only) */ - (BOOL)diskImageExistsForURL:(NSURL *)url; /** * Async check if image has already been cached * * @param url image url * @param completionBlock the block to be executed when the check is finished * * @note the completion block is always executed on the main queue */ - (void)cachedImageExistsForURL:(NSURL *)url completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Async check if image has already been cached on disk only * * @param url image url * @param completionBlock the block to be executed when the check is finished * * @note the completion block is always executed on the main queue */ - (void)diskImageExistsForURL:(NSURL *)url completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; /** *Return the cache key for a given URL */ - (NSString *)cacheKeyForURL:(NSURL *)url; @end #pragma mark - Deprecated typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); @interface SDWebImageManager (Deprecated) /** * Downloads the image at the given URL if not present in cache or return the cached version otherwise. * * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageManager.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageManager.h" #import <objc/message.h> @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation> @property (assign, nonatomic, getter = isCancelled) BOOL cancelled; @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; @property (strong, nonatomic) NSOperation *cacheOperation; @end @interface SDWebImageManager () @property (strong, nonatomic, readwrite) SDImageCache *imageCache; @property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; @property (strong, nonatomic) NSMutableSet *failedURLs; @property (strong, nonatomic) NSMutableArray *runningOperations; @end @implementation SDWebImageManager + (id)sharedManager { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (id)init { if ((self = [super init])) { _imageCache = [self createCache]; _imageDownloader = [SDWebImageDownloader sharedDownloader]; _failedURLs = [NSMutableSet new]; _runningOperations = [NSMutableArray new]; } return self; } - (SDImageCache *)createCache { return [SDImageCache sharedImageCache]; } - (NSString *)cacheKeyForURL:(NSURL *)url { if (self.cacheKeyFilter) { return self.cacheKeyFilter(url); } else { return [url absoluteString]; } } - (BOOL)cachedImageExistsForURL:(NSURL *)url { NSString *key = [self cacheKeyForURL:url]; if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; return [self.imageCache diskImageExistsWithKey:key]; } - (BOOL)diskImageExistsForURL:(NSURL *)url { NSString *key = [self cacheKeyForURL:url]; return [self.imageCache diskImageExistsWithKey:key]; } - (void)cachedImageExistsForURL:(NSURL *)url completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { NSString *key = [self cacheKeyForURL:url]; BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); if (isInMemoryCache) { // making sure we call the completion block on the main queue dispatch_async(dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(YES); } }); return; } [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch if (completionBlock) { completionBlock(isInDiskCache); } }]; } - (void)diskImageExistsForURL:(NSURL *)url completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { NSString *key = [self cacheKeyForURL:url]; [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch if (completionBlock) { completionBlock(isInDiskCache); } }]; } - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { // Invoking this method without a completedBlock is pointless NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. if ([url isKindOfClass:NSString.class]) { url = [NSURL URLWithString:(NSString *)url]; } // Prevents app crashing on argument type error like sending NSNull instead of NSURL if (![url isKindOfClass:NSURL.class]) { url = nil; } __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; __weak SDWebImageCombinedOperation *weakOperation = operation; BOOL isFailedUrl = NO; @synchronized (self.failedURLs) { isFailedUrl = [self.failedURLs containsObject:url]; } if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { dispatch_main_sync_safe(^{ NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; completedBlock(nil, error, SDImageCacheTypeNone, YES, url); }); return operation; } @synchronized (self.runningOperations) { [self.runningOperations addObject:operation]; } NSString *key = [self cacheKeyForURL:url]; operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { if (operation.isCancelled) { @synchronized (self.runningOperations) { [self.runningOperations removeObject:operation]; } return; } if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { if (image && options & SDWebImageRefreshCached) { dispatch_main_sync_safe(^{ // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. completedBlock(image, nil, cacheType, YES, url); }); } // download if no image or requested to refresh anyway, and download allowed by delegate SDWebImageDownloaderOptions downloaderOptions = 0; if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; if (image && options & SDWebImageRefreshCached) { // force progressive off if image already cached but forced refreshing downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; // ignore image read from NSURLCache if image if cached but force refreshing downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; } id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { if (weakOperation.isCancelled) { // Do nothing if the operation was cancelled // See #699 for more details // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data } else if (error) { dispatch_main_sync_safe(^{ if (!weakOperation.isCancelled) { completedBlock(nil, error, SDImageCacheTypeNone, finished, url); } }); BOOL shouldBeFailedURLAlliOSVersion = (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut); BOOL shouldBeFailedURLiOS7 = (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1 && error.code != NSURLErrorInternationalRoamingOff && error.code != NSURLErrorCallIsActive && error.code != NSURLErrorDataNotAllowed); if (shouldBeFailedURLAlliOSVersion || shouldBeFailedURLiOS7) { @synchronized (self.failedURLs) { [self.failedURLs addObject:url]; } } } else { if ((options & SDWebImageRetryFailed)) { @synchronized (self.failedURLs) { [self.failedURLs removeObject:url]; } } BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); if (options & SDWebImageRefreshCached && image && !downloadedImage) { // Image refresh hit the NSURLCache cache, do not call the completion block } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; if (transformedImage && finished) { BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:(imageWasTransformed ? nil : data) forKey:key toDisk:cacheOnDisk]; } dispatch_main_sync_safe(^{ if (!weakOperation.isCancelled) { completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url); } }); }); } else { if (downloadedImage && finished) { [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; } dispatch_main_sync_safe(^{ if (!weakOperation.isCancelled) { completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url); } }); } } if (finished) { @synchronized (self.runningOperations) { [self.runningOperations removeObject:operation]; } } }]; operation.cancelBlock = ^{ [subOperation cancel]; @synchronized (self.runningOperations) { [self.runningOperations removeObject:weakOperation]; } }; } else if (image) { dispatch_main_sync_safe(^{ if (!weakOperation.isCancelled) { completedBlock(image, nil, cacheType, YES, url); } }); @synchronized (self.runningOperations) { [self.runningOperations removeObject:operation]; } } else { // Image not in cache and download disallowed by delegate dispatch_main_sync_safe(^{ if (!weakOperation.isCancelled) { completedBlock(nil, nil, SDImageCacheTypeNone, YES, url); } }); @synchronized (self.runningOperations) { [self.runningOperations removeObject:operation]; } } }]; return operation; } - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url { if (image && url) { NSString *key = [self cacheKeyForURL:url]; [self.imageCache storeImage:image forKey:key toDisk:YES]; } } - (void)cancelAll { @synchronized (self.runningOperations) { NSArray *copiedOperations = [self.runningOperations copy]; [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; [self.runningOperations removeObjectsInArray:copiedOperations]; } } - (BOOL)isRunning { return self.runningOperations.count > 0; } @end @implementation SDWebImageCombinedOperation - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock { // check if the operation is already cancelled, then we just call the cancelBlock if (self.isCancelled) { if (cancelBlock) { cancelBlock(); } _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes } else { _cancelBlock = [cancelBlock copy]; } } - (void)cancel { self.cancelled = YES; if (self.cacheOperation) { [self.cacheOperation cancel]; self.cacheOperation = nil; } if (self.cancelBlock) { self.cancelBlock(); // TODO: this is a temporary fix to #809. // Until we can figure the exact cause of the crash, going with the ivar instead of the setter // self.cancelBlock = nil; _cancelBlock = nil; } } @end @implementation SDWebImageManager (Deprecated) // deprecated method, uses the non deprecated method // adapter for the completion block - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { return [self downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType, finished); } }]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> @protocol SDWebImageOperation <NSObject> - (void)cancel; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageManager.h" @class SDWebImagePrefetcher; @protocol SDWebImagePrefetcherDelegate <NSObject> @optional /** * Called when an image was prefetched. * * @param imagePrefetcher The current image prefetcher * @param imageURL The image url that was prefetched * @param finishedCount The total number of images that were prefetched (successful or not) * @param totalCount The total number of images that were to be prefetched */ - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; /** * Called when all images are prefetched. * @param imagePrefetcher The current image prefetcher * @param totalCount The total number of images that were prefetched (whether successful or not) * @param skippedCount The total number of images that were skipped */ - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; @end typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); /** * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. */ @interface SDWebImagePrefetcher : NSObject /** * The web image manager */ @property (strong, nonatomic, readonly) SDWebImageManager *manager; /** * Maximum number of URLs to prefetch at the same time. Defaults to 3. */ @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; /** * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. */ @property (nonatomic, assign) SDWebImageOptions options; /** * Queue options for Prefetcher. Defaults to Main Queue. */ @property (nonatomic, assign) dispatch_queue_t prefetcherQueue; @property (weak, nonatomic) id <SDWebImagePrefetcherDelegate> delegate; /** * Return the global image prefetcher instance. */ + (SDWebImagePrefetcher *)sharedImagePrefetcher; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list * * @param urls list of URLs to prefetch */ - (void)prefetchURLs:(NSArray *)urls; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list * * @param urls list of URLs to prefetch * @param progressBlock block to be called when progress updates; * first parameter is the number of completed (successful or not) requests, * second parameter is the total number of images originally requested to be prefetched * @param completionBlock block to be called when prefetching is completed * first param is the number of completed (successful or not) requests, * second parameter is the number of skipped requests */ - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; /** * Remove and cancel queued list */ - (void)cancelPrefetching; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImagePrefetcher.h" #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) #define NSLog(...) #endif @interface SDWebImagePrefetcher () @property (strong, nonatomic) SDWebImageManager *manager; @property (strong, nonatomic) NSArray *prefetchURLs; @property (assign, nonatomic) NSUInteger requestedCount; @property (assign, nonatomic) NSUInteger skippedCount; @property (assign, nonatomic) NSUInteger finishedCount; @property (assign, nonatomic) NSTimeInterval startedTime; @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; @end @implementation SDWebImagePrefetcher + (SDWebImagePrefetcher *)sharedImagePrefetcher { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (id)init { if ((self = [super init])) { _manager = [SDWebImageManager new]; _options = SDWebImageLowPriority; _prefetcherQueue = dispatch_get_main_queue(); self.maxConcurrentDownloads = 3; } return self; } - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; } - (NSUInteger)maxConcurrentDownloads { return self.manager.imageDownloader.maxConcurrentDownloads; } - (void)startPrefetchingAtIndex:(NSUInteger)index { if (index >= self.prefetchURLs.count) return; self.requestedCount++; [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!finished) return; self.finishedCount++; if (image) { if (self.progressBlock) { self.progressBlock(self.finishedCount,[self.prefetchURLs count]); } NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); } else { if (self.progressBlock) { self.progressBlock(self.finishedCount,[self.prefetchURLs count]); } NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); // Add last failed self.skippedCount++; } if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { [self.delegate imagePrefetcher:self didPrefetchURL:self.prefetchURLs[index] finishedCount:self.finishedCount totalCount:self.prefetchURLs.count ]; } if (self.prefetchURLs.count > self.requestedCount) { dispatch_async(self.prefetcherQueue, ^{ [self startPrefetchingAtIndex:self.requestedCount]; }); } else if (self.finishedCount == self.requestedCount) { [self reportStatus]; if (self.completionBlock) { self.completionBlock(self.finishedCount, self.skippedCount); self.completionBlock = nil; } self.progressBlock = nil; } }]; } - (void)reportStatus { NSUInteger total = [self.prefetchURLs count]; NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { [self.delegate imagePrefetcher:self didFinishWithTotalCount:(total - self.skippedCount) skippedCount:self.skippedCount ]; } } - (void)prefetchURLs:(NSArray *)urls { [self prefetchURLs:urls progress:nil completed:nil]; } - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { [self cancelPrefetching]; // Prevent duplicate prefetch request self.startedTime = CFAbsoluteTimeGetCurrent(); self.prefetchURLs = urls; self.completionBlock = completionBlock; self.progressBlock = progressBlock; if(urls.count == 0){ if(completionBlock){ completionBlock(0,0); } }else{ // Starts prefetching from the very first image on the list with the max allowed concurrency NSUInteger listCount = self.prefetchURLs.count; for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { [self startPrefetchingAtIndex:i]; } } } - (void)cancelPrefetching { self.prefetchURLs = nil; self.skippedCount = 0; self.requestedCount = 0; self.finishedCount = 0; [self.manager cancelAll]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. */ @interface UIButton (WebCache) /** * Get the current image URL. */ - (NSURL *)sd_currentImageURL; /** * Get the image URL for a control state. * * @param state Which state you want to know the URL for. The values are described in UIControlState. */ - (NSURL *)sd_imageURLForState:(UIControlState)state; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state; /** * Set the imageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the backgroundImageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; /** * Set the backgroundImageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; /** * Set the backgroundImageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the backgroundImageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the backgroundImageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param state The state that uses the specified title. The values are described in UIControlState. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the backgroundImageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; /** * Cancel the current image download */ - (void)sd_cancelImageLoadForState:(UIControlState)state; /** * Cancel the current backgroundImage download */ - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; @end @interface UIButton (WebCacheDeprecated) - (NSURL *)currentImageURL __deprecated_msg("Use `sd_currentImageURL`"); - (NSURL *)imageURLForState:(UIControlState)state __deprecated_msg("Use `sd_imageURLForState:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:completed:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:completed:`"); - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:completed:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:completed:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:completed:`"); - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:`"); - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelImageLoadForState:`"); - (void)cancelBackgroundImageLoadForState:(UIControlState)state __deprecated_msg("Use `sd_cancelBackgroundImageLoadForState:`"); @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIButton+WebCache.h" #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" static char imageURLStorageKey; @implementation UIButton (WebCache) - (NSURL *)sd_currentImageURL { NSURL *url = self.imageURLStorage[@(self.state)]; if (!url) { url = self.imageURLStorage[@(UIControlStateNormal)]; } return url; } - (NSURL *)sd_imageURLForState:(UIControlState)state { return self.imageURLStorage[@(state)]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { [self setImage:placeholder forState:state]; [self sd_cancelImageLoadForState:state]; if (!url) { [self.imageURLStorage removeObjectForKey:@(state)]; dispatch_main_async_safe(^{ NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; if (completedBlock) { completedBlock(nil, error, SDImageCacheTypeNone, url); } }); return; } self.imageURLStorage[@(state)] = url; __weak __typeof(self)wself = self; id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe(^{ __strong UIButton *sself = wself; if (!sself) return; if (image) { [sself setImage:image forState:state]; } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forState:state]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { [self sd_cancelImageLoadForState:state]; [self setBackgroundImage:placeholder forState:state]; if (url) { __weak __typeof(self)wself = self; id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe(^{ __strong UIButton *sself = wself; if (!sself) return; if (image) { [sself setBackgroundImage:image forState:state]; } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setBackgroundImageLoadOperation:operation forState:state]; } else { dispatch_main_async_safe(^{ NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; if (completedBlock) { completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_cancelImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (NSMutableDictionary *)imageURLStorage { NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); if (!storage) { storage = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return storage; } @end @implementation UIButton (WebCacheDeprecated) - (NSURL *)currentImageURL { return [self sd_currentImageURL]; } - (NSURL *)imageURLForState:(UIControlState)state { return [self sd_imageURLForState:state]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)cancelCurrentImageLoad { // in a backwards compatible manner, cancel for current state [self sd_cancelImageLoadForState:self.state]; } - (void)cancelBackgroundImageLoadForState:(UIControlState)state { [self sd_cancelBackgroundImageLoadForState:state]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImage+GIF.h
C/C++ Header
// // UIImage+GIF.h // LBGIFImage // // Created by Laurin Brandner on 06.01.12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (GIF) + (UIImage *)sd_animatedGIFNamed:(NSString *)name; + (UIImage *)sd_animatedGIFWithData:(NSData *)data; - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImage+GIF.m
Objective-C
// // UIImage+GIF.m // LBGIFImage // // Created by Laurin Brandner on 06.01.12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import "UIImage+GIF.h" #import <ImageIO/ImageIO.h> @implementation UIImage (GIF) + (UIImage *)sd_animatedGIFWithData:(NSData *)data { if (!data) { return nil; } CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); size_t count = CGImageSourceGetCount(source); UIImage *animatedImage; if (count <= 1) { animatedImage = [[UIImage alloc] initWithData:data]; } else { NSMutableArray *images = [NSMutableArray array]; NSTimeInterval duration = 0.0f; for (size_t i = 0; i < count; i++) { CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); duration += [self sd_frameDurationAtIndex:i source:source]; [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; CGImageRelease(image); } if (!duration) { duration = (1.0f / 10.0f) * count; } animatedImage = [UIImage animatedImageWithImages:images duration:duration]; } CFRelease(source); return animatedImage; } + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { float frameDuration = 0.1f; CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; if (delayTimeUnclampedProp) { frameDuration = [delayTimeUnclampedProp floatValue]; } else { NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; if (delayTimeProp) { frameDuration = [delayTimeProp floatValue]; } } // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> // for more information. if (frameDuration < 0.011f) { frameDuration = 0.100f; } CFRelease(cfFrameProperties); return frameDuration; } + (UIImage *)sd_animatedGIFNamed:(NSString *)name { CGFloat scale = [UIScreen mainScreen].scale; if (scale > 1.0f) { NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; NSData *data = [NSData dataWithContentsOfFile:retinaPath]; if (data) { return [UIImage sd_animatedGIFWithData:data]; } NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; data = [NSData dataWithContentsOfFile:path]; if (data) { return [UIImage sd_animatedGIFWithData:data]; } return [UIImage imageNamed:name]; } else { NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; NSData *data = [NSData dataWithContentsOfFile:path]; if (data) { return [UIImage sd_animatedGIFWithData:data]; } return [UIImage imageNamed:name]; } } - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { return self; } CGSize scaledSize = size; CGPoint thumbnailPoint = CGPointZero; CGFloat widthFactor = size.width / self.size.width; CGFloat heightFactor = size.height / self.size.height; CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; scaledSize.width = self.size.width * scaleFactor; scaledSize.height = self.size.height * scaleFactor; if (widthFactor > heightFactor) { thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; } NSMutableArray *scaledImages = [NSMutableArray array]; UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); for (UIImage *image in self.images) { [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); [scaledImages addObject:newImage]; } UIGraphicsEndImageContext(); return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h
C/C++ Header
// // UIImage+MultiFormat.h // SDWebImage // // Created by Olivier Poitrey on 07/06/13. // Copyright (c) 2013 Dailymotion. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (MultiFormat) + (UIImage *)sd_imageWithData:(NSData *)data; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m
Objective-C
// // UIImage+MultiFormat.m // SDWebImage // // Created by Olivier Poitrey on 07/06/13. // Copyright (c) 2013 Dailymotion. All rights reserved. // #import "UIImage+MultiFormat.h" #import "UIImage+GIF.h" #import "NSData+ImageContentType.h" #import <ImageIO/ImageIO.h> #ifdef SD_WEBP #import "UIImage+WebP.h" #endif @implementation UIImage (MultiFormat) + (UIImage *)sd_imageWithData:(NSData *)data { if (!data) { return nil; } UIImage *image; NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; if ([imageContentType isEqualToString:@"image/gif"]) { image = [UIImage sd_animatedGIFWithData:data]; } #ifdef SD_WEBP else if ([imageContentType isEqualToString:@"image/webp"]) { image = [UIImage sd_imageWithWebPData:data]; } #endif else { image = [[UIImage alloc] initWithData:data]; UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; if (orientation != UIImageOrientationUp) { image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:orientation]; } } return image; } +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { UIImageOrientation result = UIImageOrientationUp; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); if (imageSource) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { CFTypeRef val; int exifOrientation; val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (val) { CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; } // else - if it's not set it remains at up CFRelease((CFTypeRef) properties); } else { //NSLog(@"NO PROPERTIES, FAIL"); } CFRelease(imageSource); } return result; } #pragma mark EXIF orientation tag converter // Convert an EXIF image orientation to an iOS one. // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { UIImageOrientation orientation = UIImageOrientationUp; switch (exifOrientation) { case 1: orientation = UIImageOrientationUp; break; case 3: orientation = UIImageOrientationDown; break; case 8: orientation = UIImageOrientationLeft; break; case 6: orientation = UIImageOrientationRight; break; case 2: orientation = UIImageOrientationUpMirrored; break; case 4: orientation = UIImageOrientationDownMirrored; break; case 5: orientation = UIImageOrientationLeftMirrored; break; case 7: orientation = UIImageOrientationRightMirrored; break; default: break; } return orientation; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <UIKit/UIKit.h> #import "SDWebImageCompat.h" #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. */ @interface UIImageView (HighlightedWebCache) /** * Set the imageView `highlightedImage` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. */ - (void)sd_setHighlightedImageWithURL:(NSURL *)url; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options; /** * Set the imageView `highlightedImage` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `highlightedImage` with an `url` and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; /** * Cancel the current download */ - (void)sd_cancelCurrentHighlightedImageLoad; @end @interface UIImageView (HighlightedWebCacheDeprecated) - (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`"); - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`"); - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`"); - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`"); - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`"); - (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`"); @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+HighlightedWebCache.h" #import "UIView+WebCacheOperation.h" #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" @implementation UIImageView (HighlightedWebCache) - (void)sd_setHighlightedImageWithURL:(NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { [self sd_cancelCurrentHighlightedImageLoad]; if (url) { __weak __typeof(self)wself = self; id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe (^ { if (!wself) return; if (image) { wself.highlightedImage = image; [wself setNeedsLayout]; } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; } else { dispatch_main_async_safe(^{ NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; if (completedBlock) { completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_cancelCurrentHighlightedImageLoad { [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; } @end @implementation UIImageView (HighlightedWebCacheDeprecated) - (void)setHighlightedImageWithURL:(NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)cancelCurrentHighlightedImageLoad { [self sd_cancelCurrentHighlightedImageLoad]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIImageView. * * Usage with a UITableViewCell sub-class: * * @code #import <SDWebImage/UIImageView+WebCache.h> ... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } // Here we use the provided sd_setImageWithURL: method to load the web image // Ensure you use a placeholder image otherwise cells will be initialized with no image [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder"]]; cell.textLabel.text = @"My Text"; return cell; } * @endcode */ @interface UIImageView (WebCache) /** * Get the current image URL. * * Note that because of the limitations of categories this property can get out of sync * if you use sd_setImage: directly. */ - (NSURL *)sd_imageURL; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. */ - (void)sd_setImageWithURL:(NSURL *)url; /** * Set the imageView `image` with an `url` and a placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @see sd_setImageWithURL:placeholderImage:options: */ - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. */ - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url`, placeholder and custom options. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url` and a optionaly placeholder image. * * The download is asynchronous and cached. * * @param url The url for the image. * @param placeholder The image to be set initially, until the image request finishes. * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. * @param progressBlock A block called while image is downloading * @param completedBlock A block called when operation has been completed. This block has no return value * and takes the requested UIImage as first parameter. In case of error the image parameter * is nil and the second parameter may contain an NSError. The third parameter is a Boolean * indicating if the image was retrived from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; /** * Download an array of images and starts them in an animation loop * * @param arrayOfURLs An array of NSURL */ - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; /** * Cancel the current download */ - (void)sd_cancelCurrentImageLoad; - (void)sd_cancelCurrentAnimationImagesLoad; @end @interface UIImageView (WebCacheDeprecated) - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`"); - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+WebCache.h" #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" static char imageURLKey; @implementation UIImageView (WebCache) - (void)sd_setImageWithURL:(NSURL *)url { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; } - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { [self sd_cancelCurrentImageLoad]; objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); if (!(options & SDWebImageDelayPlaceholder)) { dispatch_main_async_safe(^{ self.image = placeholder; }); } if (url) { __weak __typeof(self)wself = self; id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe(^{ if (!wself) return; if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { completedBlock(image, error, cacheType, url); return; } else if (image) { wself.image = image; [wself setNeedsLayout]; } else { if ((options & SDWebImageDelayPlaceholder)) { wself.image = placeholder; [wself setNeedsLayout]; } } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; } else { dispatch_main_async_safe(^{ NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; if (completedBlock) { completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; } - (NSURL *)sd_imageURL { return objc_getAssociatedObject(self, &imageURLKey); } - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { [self sd_cancelCurrentAnimationImagesLoad]; __weak __typeof(self)wself = self; NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; for (NSURL *logoImageURL in arrayOfURLs) { id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_sync_safe(^{ __strong UIImageView *sself = wself; [sself stopAnimating]; if (sself && image) { NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; if (!currentImages) { currentImages = [[NSMutableArray alloc] init]; } [currentImages addObject:image]; sself.animationImages = currentImages; [sself setNeedsLayout]; } [sself startAnimating]; }); }]; [operationsArray addObject:operation]; } [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; } - (void)sd_cancelCurrentImageLoad { [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; } - (void)sd_cancelCurrentAnimationImagesLoad { [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; } @end @implementation UIImageView (WebCacheDeprecated) - (NSURL *)imageURL { return [self sd_imageURL]; } - (void)setImageWithURL:(NSURL *)url { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; } - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (completedBlock) { completedBlock(image, error, cacheType); } }]; } - (void)cancelCurrentArrayLoad { [self sd_cancelCurrentAnimationImagesLoad]; } - (void)cancelCurrentImageLoad { [self sd_cancelCurrentImageLoad]; } - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { [self sd_setAnimationImagesWithURLs:arrayOfURLs]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <UIKit/UIKit.h> #import "SDWebImageManager.h" @interface UIView (WebCacheOperation) /** * Set the image load operation (storage in a UIView based dictionary) * * @param operation the operation * @param key key for storing the operation */ - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; /** * Cancel all operations for the current UIView and key * * @param key key for identifying the operations */ - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; /** * Just remove the operations corresponding to the current UIView and key without cancelling them * * @param key key for identifying the operations */ - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m
Objective-C
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCacheOperation.h" #import "objc/runtime.h" static char loadOperationKey; @implementation UIView (WebCacheOperation) - (NSMutableDictionary *)operationDictionary { NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); if (operations) { return operations; } operations = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return operations; } - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { [self sd_cancelImageLoadOperationWithKey:key]; NSMutableDictionary *operationDictionary = [self operationDictionary]; [operationDictionary setObject:operation forKey:key]; } - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { // Cancel in progress downloader from queue NSMutableDictionary *operationDictionary = [self operationDictionary]; id operations = [operationDictionary objectForKey:key]; if (operations) { if ([operations isKindOfClass:[NSArray class]]) { for (id <SDWebImageOperation> operation in operations) { if (operation) { [operation cancel]; } } } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ [(id<SDWebImageOperation>) operations cancel]; } [operationDictionary removeObjectForKey:key]; } } - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { NSMutableDictionary *operationDictionary = [self operationDictionary]; [operationDictionary removeObjectForKey:key]; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-DXPhotoBrowser-DXSimplePhoto/Pods-DXPhotoBrowser-DXSimplePhoto-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_DXPhotoBrowser_DXSimplePhoto : NSObject @end @implementation PodsDummy_Pods_DXPhotoBrowser_DXSimplePhoto @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-DXPhotoBrowser/Pods-DXPhotoBrowser-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_DXPhotoBrowser : NSObject @end @implementation PodsDummy_Pods_DXPhotoBrowser @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-SDWebImage/Pods-SDWebImage-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_SDWebImage : NSObject @end @implementation PodsDummy_Pods_SDWebImage @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods : NSObject @end @implementation PodsDummy_Pods @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-environment.h
C/C++ Header
// To check if a library is compiled with CocoaPods you // can use the `COCOAPODS` macro definition which is // defined in the xcconfigs so it is available in // headers also when they are imported in the client // project. // DXPhotoBrowser #define COCOAPODS_POD_AVAILABLE_DXPhotoBrowser #define COCOAPODS_VERSION_MAJOR_DXPhotoBrowser 0 #define COCOAPODS_VERSION_MINOR_DXPhotoBrowser 1 #define COCOAPODS_VERSION_PATCH_DXPhotoBrowser 3 // DXPhotoBrowser-DXSimplePhoto #define COCOAPODS_POD_AVAILABLE_DXPhotoBrowser_DXSimplePhoto #define COCOAPODS_VERSION_MAJOR_DXPhotoBrowser_DXSimplePhoto 0 #define COCOAPODS_VERSION_MINOR_DXPhotoBrowser_DXSimplePhoto 1 #define COCOAPODS_VERSION_PATCH_DXPhotoBrowser_DXSimplePhoto 0 // SDWebImage #define COCOAPODS_POD_AVAILABLE_SDWebImage #define COCOAPODS_VERSION_MAJOR_SDWebImage 3 #define COCOAPODS_VERSION_MINOR_SDWebImage 7 #define COCOAPODS_VERSION_PATCH_SDWebImage 3 // SDWebImage/Core #define COCOAPODS_POD_AVAILABLE_SDWebImage_Core #define COCOAPODS_VERSION_MAJOR_SDWebImage_Core 3 #define COCOAPODS_VERSION_MINOR_SDWebImage_Core 7 #define COCOAPODS_VERSION_PATCH_SDWebImage_Core 3
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-resources.sh
Shell
#!/bin/sh set -e mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" install_resource() { case $1 in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" ;; *.framework) echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\"" xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm" ;; *.xcassets) ;; /*) echo "$1" echo "$1" >> "$RESOURCES_TO_COPY" ;; *) echo "${PODS_ROOT}/$1" echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" ;; esac } install_resource "${BUILT_PRODUCTS_DIR}/DXPhotoBrowser.bundle" install_resource "${BUILT_PRODUCTS_DIR}/DXPhotoBrowser-DXSimplePhoto.bundle" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]]; then rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ `find . -name '*.xcassets' | wc -l` -ne 0 ] then case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac find "${PWD}" -name "*.xcassets" -print0 | xargs -0 actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Example/Tests/Tests.m
Objective-C
// // DXPhotoBrowser-DXSimplePhotoTests.m // DXPhotoBrowser-DXSimplePhotoTests // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // @import XCTest; #import <DXPhotoBrowser.h> #import <DXSimplePhoto.h> @interface Tests : XCTestCase @end @implementation Tests { NSArray *_simplePhotos; } - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. NSArray *imageURLs = @[@"http://1.png", @"http://2.png", [NSURL URLWithString:@"http://www.3.com/1.png"]]; _simplePhotos = [DXSimplePhoto photosWithImageURLs:imageURLs]; } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { XCTAssert(_simplePhotos.count == 3, @"count right"); XCTAssert([[_simplePhotos valueForKey:@"imageURL"] count] == 3, @"count right"); } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXSimplePhoto.h
C/C++ Header
// // DXSimplePhoto.h // Pods // // Created by xiekw on 15/9/16. // // #import <Foundation/Foundation.h> #import "DXPhoto.h" @interface DXSimplePhoto : NSObject<DXPhoto> @property (nonatomic, strong, readonly) NSString *imageURL; + (instancetype)photoWithImageURL:(NSString *)imageURL; + (NSArray *)photosWithImageURLs:(NSArray *)imageURLs; @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
Pod/Classes/DXSimplePhoto.m
Objective-C
// // DXSimplePhoto.m // Pods // // Created by xiekw on 15/9/16. // // #import "DXSimplePhoto.h" #import "SDWebImageManager.h" @interface DXSimplePhoto () @property (nonatomic, strong) UIImage *placeholder; @end @implementation DXSimplePhoto { NSString *_imageURL; id<SDWebImageOperation> _operation; } + (instancetype)photoWithImageURL:(NSString *)imageURL { DXSimplePhoto *photo = [DXSimplePhoto new]; photo->_imageURL = imageURL; photo->_placeholder = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageURL]; return photo; } + (NSArray *)photosWithImageURLs:(NSArray *)imageURLs { if (!imageURLs || imageURLs.count == 0) return nil; NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:imageURLs.count]; for (NSString *imageURL in imageURLs) { DXSimplePhoto *simplePhoto = nil; if ([imageURL isKindOfClass:[NSString class]]) { simplePhoto = [DXSimplePhoto photoWithImageURL:imageURL]; } else if ([imageURL isKindOfClass:[NSURL class]]) { NSURL *URL = (NSURL *)imageURL; simplePhoto = [DXSimplePhoto photoWithImageURL:URL.absoluteString]; } [mArray addObject:simplePhoto]; } return mArray; } - (UIImage *)placeholder { return _placeholder; } - (CGSize)expectLoadedImageSize { return _placeholder.size; } - (void)loadImageWithProgressBlock:(DXPhotoProgressBlock)progressBlock completionBlock:(DXPhotoCompletionBlock)completionBlock { __weak typeof(self) wself = self; SDWebImageCompletionWithFinishedBlock finishBlock = ^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { wself.placeholder = image; if (completionBlock) { completionBlock(wself, image); } }; _operation = [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:_imageURL] options:1 progress:nil completed:finishBlock]; } - (void)cancelLoadImage { [_operation cancel]; _operation = nil; } @end
xiekw2010/DXPhotoBrowser-DXSimplePhoto
1
A photo instance using SDWebImage working on DXPhotoBrowser
Objective-C
xiekw2010
David Tse
Alipay
index.js
JavaScript
import minimatch from 'minimatch' export default minimatch
xiekw2010/browser-minimatch
0
minimatch running in browser
JavaScript
xiekw2010
David Tse
Alipay
rollup.config.js
JavaScript
import resolve from 'rollup-plugin-node-resolve' import commonjs from 'rollup-plugin-commonjs' import uglify from 'rollup-plugin-uglify' import node from 'rollup-plugin-node-builtins' export default [ { input: 'index.js', output: [ { file: 'dist/minimatch.js', format: 'umd', name: 'minimatch', }, ], plugins: [ commonjs(), resolve(), node(), uglify(), ], }, ]
xiekw2010/browser-minimatch
0
minimatch running in browser
JavaScript
xiekw2010
David Tse
Alipay
.eleventy.cjs
JavaScript
const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight'); module.exports = function (eleventyConfig) { eleventyConfig.addPlugin(syntaxHighlight); eleventyConfig.addPassthroughCopy('docs-src/docs.css'); eleventyConfig.addPassthroughCopy('docs-src/.nojekyll'); eleventyConfig.addPassthroughCopy( 'node_modules/@webcomponents/webcomponentsjs' ); eleventyConfig.addPassthroughCopy('node_modules/lit/polyfill-support.js'); return { dir: { input: 'docs-src', output: 'docs', }, templateExtensionAliases: { '11ty.cjs': '11ty.js', '11tydata.cjs': '11tydata.js', }, }; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
dev/index.html
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>&lt;my-element> Demo</title> <script src="../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> <script src="../node_modules/lit/polyfill-support.js"></script> <script type="module" src="../my-element.js"></script> <style> p { border: solid 1px blue; padding: 8px; } </style> </head> <body> <my-element> <p>This is child content</p> </my-element> </body> </html>
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_data/api.11tydata.js
JavaScript
/** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ const fs = require('fs'); module.exports = () => { const customElements = JSON.parse( fs.readFileSync('custom-elements.json', 'utf-8') ); return { customElements, }; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/example.11ty.cjs
JavaScript
const page = require('./page.11ty.cjs'); const relative = require('./relative-path.cjs'); /** * This template extends the page template and adds an examples list. */ module.exports = function (data) { return page({ ...data, content: renderExample(data), }); }; const renderExample = ({name, content, collections, page}) => { return ` <h1>Example: ${name}</h1> <section class="examples"> <nav class="collection"> <ul> ${ collections.example === undefined ? '' : collections.example .map( (post) => ` <li class=${post.url === page.url ? 'selected' : ''}> <a href="${relative( page.url, post.url )}">${post.data.description.replace('<', '&lt;')}</a> </li> ` ) .join('') } </ul> </nav> <div> ${content} </div> </section> `; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/footer.11ty.cjs
JavaScript
module.exports = function (data) { return ` <footer> <p> Made with <a href="https://github.com/PolymerLabs/lit-starter-ts">lit-starter-ts</a> </p> </footer>`; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/header.11ty.cjs
JavaScript
module.exports = function (data) { return ` <header> <h1>&lt;my-element></h1> <h2>A web component just for me.</h2> </header>`; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/nav.11ty.cjs
JavaScript
const relative = require('./relative-path.cjs'); module.exports = function ({page}) { return ` <nav> <a href="${relative(page.url, '/')}">Home</a> <a href="${relative(page.url, '/examples/')}">Examples</a> <a href="${relative(page.url, '/api/')}">API</a> <a href="${relative(page.url, '/install/')}">Install</a> </nav>`; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/page.11ty.cjs
JavaScript
const header = require('./header.11ty.cjs'); const footer = require('./footer.11ty.cjs'); const nav = require('./nav.11ty.cjs'); const relative = require('./relative-path.cjs'); module.exports = function (data) { const {title, page, content} = data; return ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${title}</title> <link rel="stylesheet" href="${relative(page.url, '/docs.css')}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600|Roboto+Mono"> <link href="${relative(page.url, '/prism-okaidia.css')}" rel="stylesheet" /> <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> <script src="/node_modules/lit/polyfill-support.js"></script> <script type="module" src="${relative( page.url, '/my-element.bundled.js' )}"></script> </head> <body> ${header()} ${nav(data)} <div id="main-wrapper"> <main> ${content} </main> </div> ${footer()} </body> </html>`; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/_includes/relative-path.cjs
JavaScript
const path = require('path').posix; module.exports = (base, p) => { const relativePath = path.relative(base, p); if (p.endsWith('/') && !relativePath.endsWith('/') && relativePath !== '') { return relativePath + '/'; } return relativePath; };
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/api.11ty.cjs
JavaScript
/** * This page generates its content from the custom-element.json file as read by * the _data/api.11tydata.js script. */ module.exports = class Docs { data() { return { layout: 'page.11ty.cjs', title: '<my-element> ⌲ Docs', }; } render(data) { const customElements = data.api['11tydata'].customElements; const tags = customElements.tags; return ` <h1>API</h1> ${tags .map( (tag) => ` <h2>&lt;${tag.name}></h2> <div> ${tag.description} </div> ${renderTable( 'Attributes', ['name', 'description', 'type', 'default'], tag.attributes )} ${renderTable( 'Properties', ['name', 'attribute', 'description', 'type', 'default'], tag.properties )} ${ /* * Methods are not output by web-component-analyzer yet (a bug), so * this is a placeholder so that at least _something_ will be output * when that is fixed, and element maintainers will hopefully have a * signal to update this file to add the neccessary columns. */ renderTable('Methods', ['name', 'description'], tag.methods) } ${renderTable('Events', ['name', 'description'], tag.events)} ${renderTable('Slots', ['name', 'description'], tag.slots)} ${renderTable( 'CSS Shadow Parts', ['name', 'description'], tag.cssParts )} ${renderTable( 'CSS Custom Properties', ['name', 'description'], tag.cssProperties )} ` ) .join('')} `; } }; /** * Renders a table of data, plucking the given properties from each item in * `data`. */ const renderTable = (name, properties, data) => { if (data === undefined) { return ''; } return ` <h3>${name}</h3> <table> <tr> ${properties.map((p) => `<th>${capitalize(p)}</th>`).join('')} </tr> ${data .map( (i) => ` <tr> ${properties.map((p) => `<td>${i[p]}</td>`).join('')} </tr> ` ) .join('')} </table> `; }; const capitalize = (s) => s[0].toUpperCase() + s.substring(1);
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs-src/docs.css
CSS
* { box-sizing: border-box; } body { margin: 0; color: #333; font-family: 'Open Sans', arial, sans-serif; min-width: min-content; min-height: 100vh; font-size: 18px; display: flex; flex-direction: column; align-items: stretch; } #main-wrapper { flex-grow: 1; } main { max-width: 1024px; margin: 0 auto; } a:visited { color: inherit; } header { width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 360px; margin: 0; background: linear-gradient(0deg, rgba(9,9,121,1) 0%, rgba(0,212,255,1) 100%); color: white; } footer { width: 100%; min-height: 120px; background: gray; color: white; display: flex; flex-direction: column; justify-content: center; padding: 12px; margin-top: 64px; } h1 { font-size: 2.5em; font-weight: 400; } h2 { font-size: 1.6em; font-weight: 300; margin: 64px 0 12px; } h3 { font-weight: 300; } header h1 { width: auto; font-size: 2.8em; margin: 0; } header h2 { width: auto; margin: 0; } nav { display: grid; width: 100%; max-width: 100%; grid-template-columns: repeat(auto-fit, 240px); justify-content: center; border-bottom: 1px solid #efefef; } nav > a { color: #444; display: block; flex: 1; font-size: 18px; padding: 20px 0; text-align: center; text-decoration: none; } nav > a:hover { text-decoration: underline; } nav.collection { border: none; } nav.collection > ul { padding: 0; list-style: none; } nav.collection > ul > li { padding: 4px 0; } nav.collection > ul > li.selected { font-weight: 600; } nav.collection a { text-decoration: none; } nav.collection a:hover { text-decoration: underline; } section.columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 488px)); grid-gap: 48px; justify-content: center; } section.columns > div { flex: 1; } section.examples { display: grid; grid-template-columns: 240px minmax(400px, 784px); grid-gap: 48px; justify-content: center; } section.examples h2:first-of-type { margin-top: 0; } table { width: 100%; border-collapse: collapse; } th { font-weight: 600; } td, th { border: solid 1px #aaa; padding: 4px; text-align: left; }
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs/api/index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><my-element> ⌲ Docs</title> <link rel="stylesheet" href="../docs.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600|Roboto+Mono"> <link href="../prism-okaidia.css" rel="stylesheet" /> <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> <script src="/node_modules/lit/polyfill-support.js"></script> <script type="module" src="../my-element.bundled.js"></script> </head> <body> <header> <h1>&lt;my-element></h1> <h2>A web component just for me.</h2> </header> <nav> <a href="../">Home</a> <a href="../examples/">Examples</a> <a href="">API</a> <a href="../install/">Install</a> </nav> <div id="main-wrapper"> <main> <h1>API</h1> <h2>&lt;my-element></h2> <div> An example element. </div> <h3>Attributes</h3> <table> <tr> <th>Name</th><th>Description</th><th>Type</th><th>Default</th> </tr> <tr> <td>name</td><td>The name to say "Hello" to.</td><td>string</td><td>"World"</td> </tr> <tr> <td>count</td><td>The number of times the button has been clicked.</td><td>number</td><td>0</td> </tr> </table> <h3>Properties</h3> <table> <tr> <th>Name</th><th>Attribute</th><th>Description</th><th>Type</th><th>Default</th> </tr> <tr> <td>name</td><td>name</td><td>The name to say "Hello" to.</td><td>string</td><td>"World"</td> </tr> <tr> <td>count</td><td>count</td><td>The number of times the button has been clicked.</td><td>number</td><td>0</td> </tr> <tr> <td>renderRoot</td><td>undefined</td><td>Node or ShadowRoot into which element DOM should be rendered. Defaults to an open shadowRoot.</td><td>HTMLElement | ShadowRoot</td><td>undefined</td> </tr> <tr> <td>isUpdatePending</td><td>undefined</td><td>undefined</td><td>boolean</td><td>undefined</td> </tr> <tr> <td>hasUpdated</td><td>undefined</td><td>undefined</td><td>boolean</td><td>undefined</td> </tr> <tr> <td>updateComplete</td><td>undefined</td><td>Returns a Promise that resolves when the element has completed updating. The Promise value is a boolean that is `true` if the element completed the update without triggering another update. The Promise result is `false` if a property was set inside `updated()`. If the Promise is rejected, an exception was thrown during the update. To await additional asynchronous work, override the `getUpdateComplete` method. For example, it is sometimes useful to await a rendered element before fulfilling this Promise. To do this, first await `super.getUpdateComplete()`, then any subsequent state.</td><td>Promise<boolean></td><td>undefined</td> </tr> </table> <h3>Slots</h3> <table> <tr> <th>Name</th><th>Description</th> </tr> <tr> <td></td><td>This element has a slot</td> </tr> </table> <h3>CSS Shadow Parts</h3> <table> <tr> <th>Name</th><th>Description</th> </tr> <tr> <td>button</td><td>The button</td> </tr> </table> </main> </div> <footer> <p> Made with <a href="https://github.com/PolymerLabs/lit-starter-ts">lit-starter-ts</a> </p> </footer> </body> </html>
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs/docs.css
CSS
* { box-sizing: border-box; } body { margin: 0; color: #333; font-family: 'Open Sans', arial, sans-serif; min-width: min-content; min-height: 100vh; font-size: 18px; display: flex; flex-direction: column; align-items: stretch; } #main-wrapper { flex-grow: 1; } main { max-width: 1024px; margin: 0 auto; } a:visited { color: inherit; } header { width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 360px; margin: 0; background: linear-gradient(0deg, rgba(9,9,121,1) 0%, rgba(0,212,255,1) 100%); color: white; } footer { width: 100%; min-height: 120px; background: gray; color: white; display: flex; flex-direction: column; justify-content: center; padding: 12px; margin-top: 64px; } h1 { font-size: 2.5em; font-weight: 400; } h2 { font-size: 1.6em; font-weight: 300; margin: 64px 0 12px; } h3 { font-weight: 300; } header h1 { width: auto; font-size: 2.8em; margin: 0; } header h2 { width: auto; margin: 0; } nav { display: grid; width: 100%; max-width: 100%; grid-template-columns: repeat(auto-fit, 240px); justify-content: center; border-bottom: 1px solid #efefef; } nav > a { color: #444; display: block; flex: 1; font-size: 18px; padding: 20px 0; text-align: center; text-decoration: none; } nav > a:hover { text-decoration: underline; } nav.collection { border: none; } nav.collection > ul { padding: 0; list-style: none; } nav.collection > ul > li { padding: 4px 0; } nav.collection > ul > li.selected { font-weight: 600; } nav.collection a { text-decoration: none; } nav.collection a:hover { text-decoration: underline; } section.columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 488px)); grid-gap: 48px; justify-content: center; } section.columns > div { flex: 1; } section.examples { display: grid; grid-template-columns: 240px minmax(400px, 784px); grid-gap: 48px; justify-content: center; } section.examples h2:first-of-type { margin-top: 0; } table { width: 100%; border-collapse: collapse; } th { font-weight: 600; } td, th { border: solid 1px #aaa; padding: 4px; text-align: left; }
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay
docs/examples/index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><my-element> ⌲ Examples ⌲ Basic</title> <link rel="stylesheet" href="../docs.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600|Roboto+Mono"> <link href="../prism-okaidia.css" rel="stylesheet" /> <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script> <script src="/node_modules/lit/polyfill-support.js"></script> <script type="module" src="../my-element.bundled.js"></script> </head> <body> <header> <h1>&lt;my-element></h1> <h2>A web component just for me.</h2> </header> <nav> <a href="../">Home</a> <a href="">Examples</a> <a href="../api/">API</a> <a href="../install/">Install</a> </nav> <div id="main-wrapper"> <main> <h1>Example: Basic</h1> <section class="examples"> <nav class="collection"> <ul> <li class=> <a href="name-property/">Setting the name property</a> </li> <li class=selected> <a href="">A basic example</a> </li> </ul> </nav> <div> <style> my-element p { border: solid 1px blue; padding: 8px; } </style> <my-element> <p>This is child content</p> </my-element> <h3>CSS</h3> <pre class="language-css"><code class="language-css"><span class="token selector">p</span> <span class="token punctuation">{</span><br> <span class="token property">border</span><span class="token punctuation">:</span> solid 1px blue<span class="token punctuation">;</span><br> <span class="token property">padding</span><span class="token punctuation">:</span> 8px<span class="token punctuation">;</span><br><span class="token punctuation">}</span></code></pre> <h3>HTML</h3> <pre class="language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>my-element</span><span class="token punctuation">></span></span><br> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>This is child content<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span><br><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>my-element</span><span class="token punctuation">></span></span></code></pre> </div> </section> </main> </div> <footer> <p> Made with <a href="https://github.com/PolymerLabs/lit-starter-ts">lit-starter-ts</a> </p> </footer> </body> </html>
xiekw2010/lit-component-play
0
lit component play
JavaScript
xiekw2010
David Tse
Alipay